39

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.

2
  • This might be faster than other approaches Commented Jul 17, 2015 at 18:47
  • 1
    myArray.filter(function(item , index, arr){ return arr.indexOf(item)=== index}) please ignore my previous comment , read your question incorrectly. Commented Jul 17, 2015 at 19:34

2 Answers 2

80

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;
})
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Mihai and Jurka. I was just wondering if there is any built in method to do this. Anyways you guys solved my problem. Best Regards
@YoYoSatySingh It's better to go through Set in Node.js now. The browser support is also starting to get there.
shorter version: uniques = array.filter((x, i) => i === array.indexOf(x))
49

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

1 Comment

exactly - as a oneliner in 2022: Array.from(new Set(array))

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.