Barak David
Barak David

Reputation: 45

Write a function that takes an array by calling another function to return a value and store it on a new array

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

/**

//my javascript code//

function map(array, callback) {
  for (let newArray of array) {
    value(callback(newArray));
  }
  return value;
}
export default map;

Upvotes: 0

Views: 3103

Answers (1)

Ferin Patel
Ferin Patel

Reputation: 3968

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

Upvotes: 2

Related Questions