Reputation: 926
I have an array of sequences, what i am trying to achieve is whichever last object completed property is true, then the next to next object will have is_to_happen as true
input
const sequences = [
{
"title": "Order placed",
"completed": true
},
{
"title": "To be confirmed",
"completed": false
},
{
"title": "Approx Thursday product will be shipped",
"completed": false
}
]
And this is what i want to have as an expected output
const output = [
{
"title": "Order placed",
"completed": true,
"is_to_happen": false
},
{
"title": "To be confirmed",
"completed": false,
"is_to_happen": false
},
{
"title": "Approx Thursday product will be shipped",
"completed": false,
"is_to_happen": true
}
]
What i have tried so far using array.reduce is not working
sequences.reduce((acc,curr) => {
acc = [...acc, curr]
if(curr.completed){
acc = [...acc, {...curr, is_to_happen: true}]
}
return acc
}, [])
Upvotes: 0
Views: 78
Reputation: 136114
Usea reduce
, and also keep track of the index of the completed
item:
const sequences = [
{
"title": "Order placed",
"completed": true
},
{
"title": "To be confirmed",
"completed": false
},
{
"title": "Approx Thursday product will be shipped",
"completed": false
},
{ "title": "One more step", "completed": false }
]
const result = sequences.reduce ( (acc,item, i) => {
if(item.completed) acc.completedIndex = i;
acc.items.push( {...item,"is_to_happen": (acc.completedIndex != -1) && (i >= acc.completedIndex+2) } );
return acc;
},{items:[], completedIndex:-1});
console.log(result.items);
Another way to achieve the same is to look backwards 2 elements in the original array for the completed
flag
const sequences = [
{
"title": "Order placed",
"completed": true
},
{
"title": "To be confirmed",
"completed": false
},
{
"title": "Approx Thursday product will be shipped",
"completed": false
}
]
const result = sequences.map ( (item, i) => {
return {...item, is_to_happen: !!sequences[i-2]?.completed};
});
console.log(result);
Upvotes: 1
Reputation: 686
Here's one approach:
const todo = [
{
"title": "Order placed",
"completed": true
},
{
"title": "To be confirmed",
"completed": false
},
{
"title": "Approx Thursday product will be shipped",
"completed": false
}
]
// find last completed
var lastCompleted = todo.slice().reverse().find(item => item.completed === true);
// get the index of the next to the next item.
var nextToDoIndex = todo.indexOf(lastCompleted) + 2;
// only change it if it exists.
if(todo[nextToDoIndex]) todo[nextToDoIndex] = {...todo[nextToDoIndex], is_to_happen: true }
console.log(todo)
Upvotes: 1
Reputation: 11
sequences.reduce((acc, curr) => {
if (curr.completed)
acc = [...acc, { ...curr, is_to_happen: true }]
else
acc = [...acc, { ...curr, is_to_happen: false }]
return acc
}, [])
try this.
Upvotes: -1