我有一个包含对象数组的对象。
obj = {};
obj.arr = new Array();
obj.arr.push({place:"here",name:"stuff"});
obj.arr.push({place:"there",name:"morestuff"});
obj.arr.push({place:"there",name:"morestuff"});
我想知道从数组中删除重复对象的最佳方法是什么。例如,obj.arr将变成。。。
{place:"here",name:"stuff"},
{place:"there",name:"morestuff"}
常量=[{地点:“这里”,名称:“东西”},{地点:“there”,名称:“morestuff”},{地点:“there”,名称:“morestuff”}];constfilteredArr=things.reduce((thing,current)=>{const x=thing.find(item=>item.place==current.place);如果(!x){return thing.concat([current]);}其他{归还物品;}}, []);console.log(filteredArr)
通过设置对象解决方案|根据数据类型
const seed=new Set();常量=[{地点:“这里”,名称:“东西”},{地点:“there”,名称:“morestuff”},{地点:“there”,名称:“morestuff”}];constfilteredArr=things.filter(el=>{const duplicate=已看到。有(el.place);见添加(el.place);回来复制});console.log(filteredArr)
设置对象特征
Set Object中的每个值都必须是唯一的,将检查值是否相等
根据数据类型(无论是原始值还是对象引用)设置对象存储唯一值的目的。它有四个非常有用的实例方法add、clear、has和delete。
唯一的数据类型功能(&D):。。
加法
默认情况下,它将唯一数据推送到集合中,并保留数据类型。。这意味着它可以防止将重复项推入集合,并且默认情况下还会检查数据类型。。。
has方法
有时需要检查数据项是否存在于集合和中。这是集合检查唯一id或项和数据类型的简便方法。。
删除方法
它将通过标识数据类型从集合中删除特定项。。
清除方法
它将从一个特定变量中删除所有集合项,并将其设置为空对象
Set对象还具有迭代方法和更多功能。。
更好地从这里阅读:Set-JavaScript | MDN
这里是ES6的解决方案,您只想保留最后一项。该解决方案功能强大,符合Airbnb风格。
const things = {
thing: [
{ place: 'here', name: 'stuff' },
{ place: 'there', name: 'morestuff1' },
{ place: 'there', name: 'morestuff2' },
],
};
const removeDuplicates = (array, key) => {
return array.reduce((arr, item) => {
const removed = arr.filter(i => i[key] !== item[key]);
return [...removed, item];
}, []);
};
console.log(removeDuplicates(things.thing, 'place'));
// > [{ place: 'here', name: 'stuff' }, { place: 'there', name: 'morestuff2' }]
这里有一个使用JavaScript新过滤功能的解决方案,非常简单。假设你有一个这样的数组。
var duplicatesArray = ['AKASH','AKASH','NAVIN','HARISH','NAVIN','HARISH','AKASH','MANJULIKA','AKASH','TAPASWENI','MANJULIKA','HARISH','TAPASWENI','AKASH','MANISH','HARISH','TAPASWENI','MANJULIKA','MANISH'];
filter函数将允许您为数组中的每个元素使用一次回调函数来创建一个新数组。所以你可以这样设置唯一的数组。
var uniqueArray = duplicatesArray.filter(function(elem, pos) {return duplicatesArray.indexOf(elem) == pos;});
在这种情况下,您的唯一数组将遍历重复数组中的所有值。elem变量表示数组中元素的值(mike、james、james和alex),位置是它在数组中的0索引位置(0,1,2,3…),duplicatesArray.indexOf(elem)值只是该元素在原始数组中第一次出现的索引。因此,因为元素'james'是重复的,所以当我们循环遍历duplicatesArray中的所有元素并将它们推送到uniqueArray时,第一次命中james时,我们的“pos”值为1,indexOf(elem)也为1,因此james被推送到unique Array。第二次命中James时,我们的“pos”值为2,indexOf(elem)仍然为1(因为它只找到数组元素的第一个实例),因此不会推送重复项。因此,uniqueArray只包含唯一值。
这是上述功能的演示。单击此处查看上述功能示例