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
CodePudding user response:
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:
- Your
mapdoesreturn newNotes;inside theforloop, so it returns when the loop has only done one of the elements. mapisn't calling your callback correctly.- Your callback isn't doing what the
mapfunction 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" };
});
CodePudding user response:
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);
