来点 ES6 魔法怎么样?
obj.arr = obj.arr.filter((value, index, self) =>
index === self.findIndex((t) => (
t.place === value.place && t.name === value.name
))
)
参考网址
更通用的解决方案是:
const uniqueArray = obj.arr.filter((value, index) => {
const _value = JSON.stringify(value);
return index === obj.arr.findIndex(obj => {
return JSON.stringify(obj) === _value;
});
});
使用上述属性策略代替JSON.stringify
:
const isPropValuesEqual = (subject, target, propNames) =>
propNames.every(propName => subject[propName] === target[propName]);
const getUniqueItemsByProperties = (items, propNames) =>
items.filter((item, index, array) =>
index === array.findIndex(foundItem => isPropValuesEqual(foundItem, item, propNames))
);
如果你想要的话,你可以添加一个包装器propNames
属性可以是数组或值:
const getUniqueItemsByProperties = (items, propNames) => {
const propNamesArray = Array.from(propNames);
return items.filter((item, index, array) =>
index === array.findIndex(foundItem => isPropValuesEqual(foundItem, item, propNamesArray))
);
};
允许两者getUniqueItemsByProperties('a')
and getUniqueItemsByProperties(['a']);
堆栈闪电战示例
解释
- Start by understanding the two methods used:
- 接下来,想想是什么让两个对象相等并牢记在心。
- 如果某个东西满足我们刚刚想到的标准,但它的位置不是符合该标准的对象的第一个实例,那么我们可以将其检测为重复项。
- 因此,我们可以使用上述标准来确定某物是否重复。