gpt4 book ai didi

javascript - Node : removing duplicate objects from array

转载 作者:太空宇宙 更新时间:2023-11-04 03:28:17 26 4
gpt4 key购买 nike

我有一个对象数组,我想删除重复的项目。下面讨论这个主题,但是 ES6 解决方案似乎不适用于对象: Unique values in an array

var myArray=[{fname:"Bob", sname:"Brown"},{fname:"Jill",sname:"White"},{fname:"Bob", sname:"Brown"}];
var unique = myArray.filter((v, i, a) => a.indexOf(v) === i);
/*
[ { fname: 'Bob', sname: 'Brown' },
{ fname: 'Jill', sname: 'White' },
{ fname: 'Bob', sname: 'Brown' } ]
*/
let unique = [...new Set(myArray)];
/*
[ { fname: 'Bob', sname: 'Brown' },
{ fname: 'Jill', sname: 'White' },
{ fname: 'Bob', sname: 'Brown' } ]
*/

最佳答案

使用 lodash 中的 _.uniqBy 或 _.uniqWith ;)

const _ = require('lodash');

const myArray=[{fname:"Bob", sname:"Brown"},{fname:"Jill",sname:"White"},{fname:"Bob", sname:"Brown"}];

console.log(_.uniqWith(myArray, _.isEqual));

关于javascript - Node : removing duplicate objects from array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41632450/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com