从对象数组中删除原始和重复的对象-JS [英] Remove original and duplicate from an array of objects - JS

查看:67
本文介绍了从对象数组中删除原始和重复的对象-JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组对象。

const arr = [
  { title: "sky", artist: "Jon", id: 1 },
  { title: "rain", artist: "Paul", id: 2 },
  { title: "sky", artist: "Jon", id: 1 }
];

我想基于id从数组中删除所有重复项。最终结果应该是

I would like to remove all duplicates from the array based on id. The final result should be

[{ title: "rain", artist: "Paul", id: 2 }]

如果数组为

const arr = [
  { title: "sky", artist: "Jon", id: 1  },
  { title: "rain", artist: "Paul", id: 2  },
  { title: "sky", artist: "Jon", id: 1  },
  { title: "rain", artist: "Paul", id: 2  },
];

结果应为[]。

这是我尝试的方法:

const arr = [{
    title: "sky",
    artist: "Jon",
    id: 1
  },
  {
    title: "rain",
    artist: "Paul",
    id: 2
  },
  {
    title: "sky",
    artist: "Jon",
    id: 1
  }
];
const uniqueScenarios = Array.from(new Set(arr.map(a => a.id)))
  .map(id => {
    return arr.find(a => a.id === id)
  })

console.log(uniqueScenarios)

const arr1 = [{
    title: "sky",
    artist: "Jon",
    id: 1
  },
  {
    title: "rain",
    artist: "Paul",
    id: 2
  },
  {
    title: "sky",
    artist: "Jon",
    id: 1
  },
  {
    title: "rain",
    artist: "Paul",
    id: 2
  }
];
const uniqueScenarios1 = Array.from(new Set(arr1.map(a => a.id)))
  .map(id => {
    return arr1.find(a => a.id === id)
  })

console.log(uniqueScenarios1)

请提出建议。我也乐于接受lodash解决方案。这是我期望的最终解决方案。我可以添加 Stackblitz链接

Please advice. I am open to lodash solutions as well. This is the final solution I am expecting. I am able to add Stackblitz link

推荐答案

那是一个单行代码:

list.filter(el => list.filter(e => e.title == el.title).length == 1);

const arr = [{
    title: "sky",
    artist: "Jon",
    id: 1
  },
  {
    title: "rain",
    artist: "Paul",
    id: 2
  },
  {
    title: "sky",
    artist: "Jon",
    id: 1
  }
];

const arr1 = [{
    title: "sky",
    artist: "Jon",
    id: 1
  },
  {
    title: "rain",
    artist: "Paul",
    id: 2
  },
  {
    title: "sky",
    artist: "Jon",
    id: 1
  },
  {
    title: "rain",
    artist: "Paul",
    id: 2
  }
];


function removeDupes(list) {
  return list.filter(el => list.filter(e => e.id == el.id).length == 1);
}

console.log(removeDupes(arr));
console.log(removeDupes(arr1));

这篇关于从对象数组中删除原始和重复的对象-JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆