Reputation: 29
array called 'notes' contains 5 objects , each object has keys
var notes = [
{
title: "Home",
message: "is a good story",
status: 'new',
author:"dala",
},
{
title: "School",
message: "Have to go everday",
status: 'new',
author:"aisha",
},
{
title: "study",
message: "we have exam to pass",
status: 'new',
author:"Omar",
},
{
title: "Work",
message: "dead line is close",
status: 'new',
author:"Said",
},
{
title: "homework",
message: "as today we need to do it",
status: 'new',
author:"Amal",
},
];
i want to update all the notes's status to be 'completed', the error is the code only update the first Object
function map(notes,callback){
const newNotes =[];
for(var i=0; i<notes.length; i++) {
const result = callback(notes[i].status = "completed",i);
newNotes.push(result);
return newNotes;
}
}
var outp = map(notes,function(value, i){
console.log(i)
for(var a= 0; a<value.length; a++){
return notes;
}
})
console.log(outp);
I was training on the callback function, and this training code was the face of a problem writing the code If you have useful resources to learn from, please share them with me
Upvotes: 0
Views: 663
Reputation: 1055
In the map function you returned
the newNotes
array within the for loop instead of after it. However I would suggest to use the built in map
function.
var notes = [
{
title: "Home",
message: "is a good story",
status: 'new',
author:"dala",
},
{
title: "School",
message: "Have to go everday",
status: 'new',
author:"aisha",
},
{
title: "study",
message: "we have exam to pass",
status: 'new',
author:"Omar",
},
{
title: "Work",
message: "dead line is close",
status: 'new',
author:"Said",
},
{
title: "homework",
message: "as today we need to do it",
status: 'new',
author:"Amal",
},
];
function map(notes,callback){
const newNotes =[];
for(var i=0; i<notes.length; i++) {
const result = callback(notes[i].status = "completed",i);
newNotes.push(result);
}
return newNotes;
}
var outp = map(notes,function(value, i){
console.log(i)
for(var a= 0; a<value.length; a++){
return notes;
}
})
console.log(outp);
Upvotes: 1
Reputation: 1074138
You don't need to write your own map
function, Array.prototype.map
already does what your map
function does (and a bit more, but that's not relevant).
The problem is:
map
does return newNotes;
inside the for
loop, so it returns when the loop has only done one of the elements.map
isn't calling your callback correctly.map
function expects it to.The call to your callback should be just:
const result = callback(notes[i], i);
And the return newNotes;
should be after the loop.
Then your callback should create a new object with the properties from the original object passed in, plus status: "completed"
— perhaps using an object literal with spread syntax, like this:
const output = map(notes, function(note, index) {
return {...note, status: "completed" };
});
Upvotes: 2