这个问题在这里已有答案:
是否有任何方法可以通过ES6的1方法将对象唯一地推送到数组?
MyArray.pushUniquely(x);
MyMethod(x) {
if ( MyArray.IndexOf(x) === -1 )
MyArray.Push(x);
}
是否有任何方法可以通过ES6独特推送?
使用Set
集合而不是数组。
var mySet = new Set([1, 2, 3]);
mySet.add(4);
mySet.add(3);
mySet.add(0)
console.log(Array.from(mySet))
使用includes
(我已经扩展了一个方法,所以你可以在所有数组上使用它):
Array.prototype.pushUnique(item) {
if (!this.includes(item)) this.push(item);
}
或者,使用Set
:
mySet.add(x); //Will only run if x is not in the Set
您可以使用lodash uniq方法。
var uniq = _.uniq([1,2,3,4,5,3,2,4,5,1])
console.log(uniq)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
如果数组是一个对象数组,则可以执行此操作
const arr = [{
name: 'Robert',
age: 26
},
{
name: 'Joshua',
age: 69
}
]
Array.prototype.pushUniquely = function (item) {
const key = 'name';
const index = this.findIndex(i => i[key] === item[key]);
if (index === -1) this.push(item);
}
arr.pushUniquely({
name: 'Robert',
age: 24
});
console.log(arr);
如果它只是一个字符串或数字的数组,那么你可以这样做:
Array.prototype.pushUniquely = function (item) {
if (!this.includes(item)) this.push(item);
}