首页 > 解决方案 > 如何通过新集合从对象中获取唯一数组?

问题描述

如何通过新集合从对象中获取唯一数组?

我有一个包含对象的数组,我怎样才能获得一个唯一的数组,但只能保留 id?

IE:[{id: 1, title: 'test1'}, {id: 2, title: 'test2'}]

const arr = [{id: 1, title: 'test1'}, {id: 2, title: 'test2'}, {id: 1: title: 'test1'}]
const filtered = arr.filter((item) => item.title)
const result = Array.from(new set(arr))

标签: javascriptreactjs

解决方案


您可以获取一个哈希表并获取它的值。

这种方法将最后找到的对象与相同的id.

const
    array = [{ id: 1, title: 'first' }, { id: 2, title: 'test2' }, { id: 1, title: 'last' }],
    unique = Object.values(array.reduce((r, o) => (r[o.id] = o, r), {}));

console.log(unique);

通过使用Set带有闭包的 a,您可以过滤数组。

这种方法采用与第一个找到的对象相同的id.

const
    array = [{ id: 1, title: 'first' }, { id: 2, title: 'test2' }, { id: 1, title: 'last' }],
    unique = array.filter((s => ({ id }) => !s.has(id) && s.add(id))(new Set));

console.log(unique);


推荐阅读