Reputation: 55
I have some problems with understanding how callback function should work. I wanted to do a function that works just like map method. Even though I don't recive any errors, elements in array don't change. Could you point what am I doing wrong?
function multiplyFn(x) {
return x * 2;
}
const exampleArray = [1, 2, 3, 4, 5, 6, 8];
function mapFn(array, callback) {
for (const el of array) {
callback(el);
console.log(el)
}
console.log(array)
return array;
}
mapFn(exampleArray, multiplyFn);
Upvotes: 1
Views: 132
Reputation: 13
If you want to implement your own map function, you can do it without using any of the in-built array methods
//Define your map method in the Array prototype object
Array.prototype.mymap = function(callback) {
const res = [];
for (let index = 0; index < this.length; index++) {
res[index] = callback(this[index], index, this);
}
return res;
}
const exampleArray = [1, 2, 3, 4, 5, 6, 8];
//Let's test with two examples
function multiplyFn(x) {
return x * 2;
}
const first = exampleArray.mymap(multiplyFn)
console.log(first)
const second = exampleArray.mymap((el, index, array) => ({el, index}))
console.log(second)
Upvotes: 0
Reputation: 622
if you want to change the original array you can update the index of the array arguments that you pass in function.
function mapFn(array, callback) {
array.forEach(function(element,index){
let val= callback(element)
array[index] = val
});
return array;
}
Upvotes: 1
Reputation: 171690
Note you can do this simply using Array#map() which will not update original but return a new array
function multiplyFn(x) {
return x * 2;
}
const exampleArray = [1, 2, 3, 4, 5, 6, 8];
function mapFn(array, callback) {
return array.map(callback);
}
console.log(mapFn(exampleArray, multiplyFn));
Upvotes: 0
Reputation: 28424
You need to update the elements by the returned values:
function multiplyFn(x) {
return x * 2;
}
let exampleArray = [1, 2, 3, 4, 5, 6, 8];
function mapFn(array, callback) {
for (let i = 0; i < array.length; i++) {
let el = array[i];
array[i] = callback(el);
}
return array;
}
mapFn(exampleArray, multiplyFn);
Upvotes: 0