JavaScript删除具有重复属性的数组对象,同时保持最新出现

uqcuzwp8  于 12个月前  发布在  Java
关注(0)|答案(5)|浏览(131)

我已经搜索了很多,但找不到任何符合我的要求。
我想删除所有重复的条目,但保留最后一个条目而不是第一个条目。
数组已经预排序了,我不想弄乱排序
它看起来像这样:

[{
    name:"Joe",
    status:"foo1" },
  {
    name:"Joe",
    status:"foo2"},
  {
     name:"Vani",
    status:"foo5"
  }]

字符串
预期输出如下所示:

[{
    name:"Joe",
    status:"foo2"},
  {
     name:"Vani",
    status:"foo5"
  }]


如果有人能帮助我,我将感激不尽!

ubby3x7f

ubby3x7f1#

您可以使用reduce

let arr = [{ name:"Joe", status:"foo1" }, { name:"Joe", status:"foo2"}, { name:"Vani", status:"foo5" }]

let op = arr.reduce((op,inp)=>{
  op[inp.name] = inp
  return op
},{})

console.log(Object.values(op))

字符串

jfewjypa

jfewjypa2#

您可以使用ES6 Map。从Docs开始:
Map对象保存键-值对,并记住键的原始插入顺序。任何值(对象和原始值)都可以用作键或值。

const data = [
  { name:"Joe", status:"foo1" },
  { name:"Joe", status:"foo2" },
  { name:"Vani", status:"foo5" }
];

const removeDupes = (arr, map = new Map()) => {
  arr.forEach(o => map.set(o.name, o));

  return [...map.values()];
};

console.log(removeDupes(data));

个字符

k5hmc34c

k5hmc34c3#

尝试使用简单的forEach

const arr = [{ name:"Joe", status:"foo1" }, { name:"Joe", status:"foo2"}, { 
    name:"Vani", status:"foo5" }];

let result = {};
arr.forEach((val) => { result[val.name] = val; });

console.log(Object.values(result));

字符串
希望这对你有帮助…

1cklez4t

1cklez4t4#

接受的答案实际上并不保持顺序,它在最初找到的索引处修改对象
你可以把它修改成这样:

const data = [
  { name:"Joe", status:"foo1" },
  { name:"Vani", status:"foo2" },
  { name:"Joe", status:"foo3" }
];

const removeDupes = (arr, map = new Map()) => {
  arr.forEach((o, i) => map.set(o.name, {...o, order: i}));

  return [...map.values()].sort((a, b) => a.order - b.order);
};

console.log(removeDupes(data));

字符串
或者做一些更简单的事情,比如:

const data = [
  { name:"Joe", status:"foo1" },
  { name:"Vani", status:"foo2" },
  { name:"Joe", status:"foo3" }
];

let newData = [];
data.forEach(x => {
  newData = newData.filter(y => y.name != x.name);
  newData.push(x);
});

console.log(newData);


我会让其他人想出更好的解决方案...

iugsix8n

iugsix8n5#

// remove duplicate while preserve order
array.filter((row, i, arr) => arr.slice(0, i).findIndex((l) => l === row) === -1)
// change `l === row` to your own comparison logic

字符串
在您的案例中:

const data = [
  {
    name:"Joe",
    status:"foo1"
  },
  {
    name:"Joe",
    status:"foo2"
  },
  {
    name:"Vani",
    status:"foo5"
  }
];

const duplicateRemoved = data
  .toReversed()
  .filter((row, i, arr) => arr.slice(0, i).findIndex((l) => l.name === row.name) === -1)
  .toReversed();

相关问题