38

I have an array:

[
    1029,
    1008,
    1040,
    1019,
    1030,
    1009,
    1041,
    1020,
    1031,
    1010,
    1042,
    1021,
    1030,
    1008,
    1045,
    1019,
    1032,
    1009,
    1049,
    1022,
    1031,
    1010,
    1042,
    1021,
]

Now I want to remove all the duplicates from it. Is there any method in NodeJs which can directly do this.

Yo Yo Saty Singh
  • 539
  • 1
  • 6
  • 15
  • This might be faster than other approaches – Davet Jul 17 '15 at 18:47
  • 1
    myArray.filter(function(item , index, arr){ return arr.indexOf(item)=== index}) please ignore my previous comment , read your question incorrectly. – Davet Jul 17 '15 at 19:34

2 Answers2

77

No, there is no built in method in node.js, however there are plenty of ways to do this in javascript. All you have to do is look around, as this has already been answered.

uniqueArray = myArray.filter(function(elem, pos) {
    return myArray.indexOf(elem) == pos;
})
Community
  • 1
  • 1
mihai
  • 37,072
  • 9
  • 60
  • 86
47

No there is no built in method to get from array unique methods, but you could look at library called lodash which has such great methods _.uniq(array).

Also, propose alternative method as the Node.js has now support for Set's. Instead of using 3rd party module use a built-in alternative.

var array = [
    1029,
    1008,
    1040,
    1019,
    1030,
    1009,
    1041,
    1020,
    1031,
    1010,
    1042,
    1021,
    1030,
    1008,
    1045,
    1019,
    1032,
    1009,
    1049,
    1022,
    1031,
    1010,
    1042,
    1021,
];

var uSet = new Set(array);
console.log([...uSet]); // Back to array
Risto Novik
  • 8,199
  • 9
  • 50
  • 66