对象数据同时去重

如何对以下原数据进行去重?

[
    {status: 0, ids: [11, 12, 14, 15]},
    {status: 1, ids: [12, 13, 16, 15]},
    {status: 0, ids: [16, 17, 18, 15, 14]},
    {status: 2, ids: [12, 19, 20, 21]},
    {status: 1, ids: [22, 23, 24, 13, 15]},
    {status: 2, ids: [12, 26, 19, 27]}
]

期望得到数据

[
    {status: 0, ids: [11, 12, 14, 15, 16, 17, 18]},
    {status: 1, ids: [12, 13, 16, 15, 22, 23, 24]},
    {status: 2, ids: [12, 19, 20, 21, 26, 27]}
]
阅读 1.7k
3 个回答

达到这个效果没啥难度,但如果你要说什么优雅的话....

  var arr = [
    { status: 0, ids: [11, 12, 14, 15] },
    { status: 1, ids: [12, 13, 16, 15] },
    { status: 0, ids: [16, 17, 18, 15, 14] },
    { status: 2, ids: [12, 19, 20, 21] },
    { status: 1, ids: [22, 23, 24, 13, 15] },
    { status: 2, ids: [12, 26, 19, 27] }
  ]

  const arr1 = []
  JSON.parse(JSON.stringify(arr)).forEach(row => {
    const newRow = arr1.find(v => v.status === row.status)
    if (newRow) {
      newRow.ids = Array.from(new Set([...row.ids, ...newRow.ids]))
    } else {
      arr1.push(row)
    }
  })

  console.log('新数组: ', arr1);
  console.log('原数据:', arr);

如果考虑时间复杂度的话就先转换成object

const list = [
  {status: 0, ids: [11, 12, 14, 15]},
  {status: 1, ids: [12, 13, 16, 15]},
  {status: 0, ids: [16, 17, 18, 15, 14]},
  {status: 2, ids: [12, 19, 20, 21]},
  {status: 1, ids: [22, 23, 24, 13, 15]},
  {status: 2, ids: [12, 26, 19, 27]}
]

const map = {};
list.forEach(({status, ids}) => {
  map[status] = Array.from(new Set([...(map[status] || []), ...ids]));
})
const newList = Object.keys(map).map(key => (
  {
    status: key,
    ids: map[key]
  }
));
console.log(newList)
        let arr = [
            { status: 0, ids: [11, 12, 14, 15] },
            { status: 1, ids: [12, 13, 16, 15] },
            { status: 0, ids: [16, 17, 18, 15, 14] },
            { status: 2, ids: [12, 19, 20, 21] },
            { status: 1, ids: [22, 23, 24, 13, 15] },
            { status: 2, ids: [12, 26, 19, 27] },
        ];
        let arr1 = arr.reduce((a, b) => {
            let findIndex = a.findIndex((item) => item.status === b.status);
            if (findIndex > -1) {
                a[findIndex].ids = [...new Set(a[findIndex].ids.concat(b.ids))];
            } else {
                a.push(b);
            }
            return a;
        }, []);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题