0

I'm having trouble with my code for this javascript exercise as follows:

/**

  • In the function, accept an array, and call the callback on each element of the array
  • the callback will return a value - use this value and store it in a new array
  • for each iteration, the value returned from the callback, should replace the value in the previous array
  • you should return the new array with the new value
  • example:
  • const numbers = [1,2,3,4,5];
  • const newNumbers = map(numbers, (number) => {
  • return number + 3;
  • });
  • console.log(newNumbers); // [4,5,6,7,8];
  • @param {number[]} array
  • @param {Function} callback */

//my javascript code//

function map(array, callback) {
  for (let newArray of array) {
    value(callback(newArray));
  }
  return value;
}
export default map;
1
  • 1
    What is the use of generating a new array (step 2) and changing the original one (step 3)? Commented Oct 20, 2021 at 11:09

1 Answer 1

2

You can simply push callback return into array and return that same array from your custom fucntion.

You can also modify original array using index.

const customMap = (arr, callback) => {
  const finalArr = []
  arr.forEach((item, index) => {
    const res = callback(item)
    finalArr.push(res)
    arr[index] = res // This will modify original array
  })

  return finalArr
}


const numbers = [1, 2, 3, 4, 5];

const newNumbers = customMap(numbers, (number) => {
  return number + 3;
});

console.log(newNumbers);
console.log(numbers);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.