1

Is there any method to push object to array uniquely with 1 method by ES6 ?

For Ex:

MyArray.pushUniquely(x);

Or good to use old version like ? :

MyMethod(x) {

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

}

Is there any method to push uniquely by ES6 ?

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
canmustu
  • 2,304
  • 4
  • 21
  • 34
  • Since you tagged this with `mongo-shell`, it may be worth noting that MongoDB has the [`$.addToSet` operator](https://docs.mongodb.com/manual/reference/operator/update/addToSet/#up._S_addToSet) for collections. – p.s.w.g Feb 19 '19 at 01:49
  • I have to use iterative query at this situation. Querying, then taking some ids, and then querying again. Finally, i have to reduce all of them as unique. – canmustu Feb 19 '19 at 03:12

4 Answers4

2

Use a Set collection instead of an array.

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

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

console.log(Array.from(mySet))
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
1

Use includes (I've made an extension of a method so you can use it on all arrays):

Array.prototype.pushUnique(item) {
    if (!this.includes(item)) this.push(item);
}

Alternatively, use a Set:

mySet.add(x); //Will only run if x is not in the Set
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
1

You can use lodash uniq method.

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>
arunmmanoharan
  • 2,535
  • 2
  • 29
  • 60
1

If the array is an array of objects you can do

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);

If it's just an array of string or number then you can do:

Array.prototype.pushUniquely = function (item) {
    if (!this.includes(item)) this.push(item);
}
wobsoriano
  • 12,348
  • 24
  • 92
  • 162