最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Filter an array of objects to only have the last occurrence of that object with the same certain property - Stack O

programmeradmin3浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 5
var 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...

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论