是否有任何方法将对象推送到阵列? [重复]

问题描述 投票:1回答:4

这个问题在这里已有答案:

是否有任何方法可以通过ES6的1方法将对象唯一地推送到数组?

对于Ex:

MyArray.pushUniquely(x);

还是好用旧版本? :

MyMethod(x) {

    if ( MyArray.IndexOf(x) === -1 )
        MyArray.Push(x);

}

是否有任何方法可以通过ES6独特推送?

javascript arrays ecmascript-6 mongo-shell
4个回答
2
投票

使用Set集合而不是数组。

var mySet = new Set([1, 2, 3]);

mySet.add(4);
mySet.add(3);
mySet.add(0)

console.log(Array.from(mySet))

1
投票

使用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

1
投票

您可以使用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>

1
投票

如果数组是一个对象数组,则可以执行此操作

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.