The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]
Now, how we can create our own map function from scratch
function map(array, cb) {
let result = [];
for(let i = 0; i < array.length; i++) {
result.push(cb(array[i], array, i))
}
return result;
}
console.log(map([1, 2, 3], (element) => element + 1)) // [ 2, 3, 4 ]
If you like this post, I can implement more array or object methods.
See you!!