Reputation: 2292
I have a json data like this.
[{
"name": "Peter",
"age": 30,
"hair color": "brown"
}, {
"name": "Steve",
"age": 55,
"hair color": "blonde"
}, {
"name": "Steve",
"age": 25,
"hair color": "black"
}]
My code it does is, It will identify the duplicate and remove the second occurrence.
The code is :
var qdata = [{
"name": "Peter",
"age": 30,
"hair color": "brown"
}, {
"name": "Steve",
"age": 55,
"hair color": "blonde"
}, {
"name": "Steve",
"age": 25,
"hair color": "black"
}]
data = qdata.filter((obj, pos, arr) => {
return arr.map(mapObj =>
mapObj.name).indexOf(obj.name) == pos;
});
console.log(data);
Output will be :
[
{ name: 'Peter', age: 30, 'hair color': 'brown' },
{ name: 'Steve', age: 55, 'hair color': 'blonde' }
]
Here it deletes the second occurrence and keeps the first one, But what I would like to get is remove the first occurrence and keep the second one
[
{ name: 'Peter', age: 30, 'hair color': 'brown' },
{ name: 'Steve', age: 25, 'hair color': 'black' }
]
How can I do that ? Please help
Upvotes: 0
Views: 60
Reputation: 2509
You can simply reverse the array and do what you want and reverse the result to match with your expected result.
qdata.reverse();
data = qdata.filter((obj, pos, arr) => {
return arr.map(mapObj => mapObj.name).indexOf(obj.name) == pos;
});
console.log(data.reverse());
if you don't want to do that you can use the below code to get desired result.
data = [];
qdata.map((i) => {
index = data.findIndex((u) => u.name === i.name);
if (index >= 0) {
data.splice(index, 1, i);
} else {
data.push(i);
}
});
console.log(data);
Upvotes: 1