0
votes

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
What is the use of generating a new array (step 2) and changing the original one (step 3)? - JavaScript

1 Answers

1
votes

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);