I need to get a property added based on the one of the array property. Since already I am looping through the array is there a simple way to achieve below output from the input, Also I don't want to make the input array mutated
Input array
const a = [{is_done: true, name: 'a'}, {is_done: true, name: 'b'}, {is_done: true, name: 'c'}]
Output array
[
{
"is_done": true,
"name": "a",
"which_is_last_done": false
},
{
"is_done": true,
"name": "b",
"which_is_last_done": false
},
{
"is_done": true,
"name": "c",
"which_is_last_done": true
}
]
I am able to achieve this output using the below snippet, is there a better way.
const a = [{
is_done: true,
name: 'a'
}, {
is_done: true,
name: 'b'
}, {
is_done: true,
name: 'c'
}];
const output = a.reduce(
(acc, item, i, array) => {
acc.items.push({
...item,
which_is_last_done: [...array].reverse().find(item => item.is_done)?.name === item.name,
});
return acc;
}, {
items: []
}
);
console.log(output.items)
which_is_done_last: falseto all the elements. Then find the last element that's done and change it totrue.