Reputation: 127
I have an array of objects:
[{
id: 1,
cod: '123',
val: true
},
{
id: 2,
cod: '123',
val: true
},
{
id: 3,
cod: '123',
val: true
},
{
id: 4,
cod: '456',
val: true
},
{
id: 5,
cod: '456',
val: true
}]
I need to maintain the val
property true
for the objects which have the same cod
and have the higher id. For example, I'd need the following output:
[{
id: 1,
cod: '123',
val: false
},
{
id: 2,
cod: '123',
val: false
},
{
id: 3,
cod: '123',
val: true
},
{
id: 4,
cod: '456',
val: false
},
{
id: 5,
cod: '456',
val: true
}]
How could I change this array in order to obtain the desired results? Should I use filter? I'm a little lost.
Upvotes: 1
Views: 33
Reputation: 816404
You need to process and mutate every element in the array (assuming in-place mutation is fine), so .filter
is not suitable here, since it usually just "removes" elements.
A general approach would be: Iterate over every element of the array and keep a cod => previous item
map to keep track of the previous item with the same cod
value. Set val
of the current item to true
, set val
of the previous item with the same cod
value to false
, update tracking entry for current item's cod
value.
Example:
const data = [{
id: 1,
cod: '123',
val: true
},
{
id: 2,
cod: '123',
val: true
},
{
id: 3,
cod: '123',
val: true
},
{
id: 4,
cod: '456',
val: true
},
{
id: 5,
cod: '456',
val: true
}];
const previousCod = new Map();
for (const item of data) {
if (previousCod.has(item.cod)) {
previousCod.get(item.cod).val = false;
}
// Can be omitted if the initial value is guaranteed to be `true`
item.val = true;
previousCod.set(item.cod, item);
}
console.log(data);
Upvotes: 1