使用Set从数组中删除重复项,并保持最高ID

时间:2019-07-12 23:46:08

标签: javascript arrays typescript ionic-framework ecmascript-6

我有这个数组:

array = [{id: 1, name: 'apple'}, {id: 2, name: 'banana'}, {id: 3, name: 
'apple'}]

我需要删除具有重复属性“名称”的对象,并且需要为其余对象保留最高ID,例如:

newarray = [ {id: 2, name: 'banana'}, {id: 3, name: apple}]

我已经尝试过这种方式:

array = [{id: 1, name: 'apple'}, {id: 2, name: 'banana'}, {id: 3, name: 
apple}]

newarray = Array.from(new Set(array.map(x => x.id)))
                 .map(id => {
                   return {
                     id: id,
                     name: array.find( s => s.id === id).name
})

我得到的结果

newarray = [ {id: 2, name: 'banana'}, {id: 1, name: apple}]

我删除了重复的对象,但是我没有获得每个剩余对象的最高ID。

感谢给我一个主意。

3 个答案:

答案 0 :(得分:5)

我将改用reduce-简化为按名称索引的对象,该对象的值是关联的id / name对象。如果某个对象已经存在一个给定的名称,则只有在新对象的ID较高时才重新分配该对象:

const array = [{id: 1, name: 'apple'}, {id: 2, name: 'banana'}, {id: 3, name: 
'apple'}];

const newArray = Object.values(
  array.reduce((a, item) => {
    const { name } = item;
    if (!a[name] || a[name].id < item.id) {
      a[name] = item;
    }
    return a;
  }, {})
);
console.log(newArray);

答案 1 :(得分:0)

我设法使用了map,filter和reduce的组合:)

代码注释中的说明。

请参见下面的演示

var array = [{
  id: 1,
  name: 'apple'
}, {
  id: 2,
  name: 'banana'
}, {
  id: 5,
  name: 'banana'
}, {
  id: -9,
  name: 'pear'
}, {
  id: 3,
  name: 'apple'
}, {
  id: -3,
  name: 'pear'
}];

/*
  1 - it creates a Set from mapping original array into a list of names
  2 - it then maps it back into the objects but this time 
     2.1 - it filters the original array to elements with only matching names
     2.2 - and then it reduces the id to the highest value
*/
var filteredArray = Array.from(new Set(array.map(x => x.name))).map(e => {
  return {
    id: array.filter(function(el){
      return el.name == e;
    }).reduce((curr, next) => curr.id > next.id ? curr.id : next.id, 0),
    name: e
  }
});

console.log(filteredArray);

答案 2 :(得分:0)

您也可以使用pyinstaller script.spec sort来获得所需的结果

reduce