How would you filter an array of objects to only have the last occurrence of that object with the same prop of foo? I.e
given:
[
{foo:1,id:1},
{foo:1,id:2},
{foo:2,id:3}
]
I want this back:
[
{foo:1,id:2},
{foo:2,id:3}
I'm using es6 so I can start from here:
this.data.filter((item,index,self)=> {
return self.findIndex(o => o.foo === item.foo);
})
How would you filter an array of objects to only have the last occurrence of that object with the same prop of foo? I.e
given:
[
{foo:1,id:1},
{foo:1,id:2},
{foo:2,id:3}
]
I want this back:
[
{foo:1,id:2},
{foo:2,id:3}
I'm using es6 so I can start from here:
this.data.filter((item,index,self)=> {
return self.findIndex(o => o.foo === item.foo);
})
Share
Improve this question
edited Apr 14, 2017 at 10:54
SuperUberDuper
asked Apr 14, 2017 at 10:50
SuperUberDuperSuperUberDuper
9,64310 gold badges41 silver badges74 bronze badges
1
-
Create a map by
foo
's value – gurvinder372 Commented Apr 14, 2017 at 10:54
4 Answers
Reset to default 5var index = {};
var data = [{foo:1,id:1},{foo:1,id:2},{foo:2,id:3}];
data.forEach(item => index[item.foo] = item);
index[1];
// {foo:1,id:2}
Object.values(index)
// [{foo:1,id:2},{foo:2,id:3}]
Create a map by foo
's value
var map = {};
var arr = [
{foo:1,id:1},
{foo:1,id:2},
{foo:2,id:3}
];
arr.forEach( function(item){
map[ item.foo ] = item;
});
and now finally just get the map's values
var finalArray = Object.keys( map ).map( function(key){
return map[key];
});
var arr = [{foo:1, id:1}, {foo:1, id:2}, {foo:2, id:3}, {foo:2, id:4}, {foo:2, id:5}, {foo:3, id:6}],
e = {};
arr.forEach(v => e[v.foo] = v.id);
var res = Object.keys(e).map(v => arr.find(c => c.id == e[v]));
console.log(res);
In just O(n) time you can achieve this job by the .rightReduce()
functionality with an initial value tuple holding both the result and a hash.
function lastWithProp(a,p){
return a.reduceRight((r,o) => r[1][p+o[p]] ? r : (r[1][p+o[p]] = true, r[0].push(o),r), [[],{}])[0];
}
var data = [{foo:1,id:1},{foo:1,id:2},{foo:2,id:3}],
result = lastWithProp(data,"foo");
console.log(result);
The .rightReduce()
initial value (the r
argument of the callback) is a tuple (a double/triple/quadruple... group of different type of data zipped together) like [[],{}]
in this case. r[0]
holds the result as it forms through the iterations of .rightReduce()
and r[1]
holds a hash map of the met objects property value keystring if never met before. So the first time we meet {foo:1,...}
we mark it in the hash (r[1]
) like "foo1" = true
(r[1][p+o[p]] = true
). So on...