2 回答

TA貢獻(xiàn)1852條經(jīng)驗 獲得超1個贊
您可以使用哈希表并獲取它的值。
這種方法采用最后找到的具有相同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 ,您可以過濾數(shù)組。
這種方法采用第一個找到的具有相同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);

TA貢獻(xiàn)1805條經(jīng)驗 獲得超9個贊
比起集合,Map 可能更好,只需創(chuàng)建一個以 id 為鍵的映射即可。
例如。
const arr = [{id: 1, title: 'test1'}, {id: 2, title: 'test2'}, {id: 1, title: 'test1'}];
const d = new Map(arr.map(m => [m.id, m]));
console.log([...d.values()]);
添加回答
舉報