Tuesday, 30 June 2015

JavaScript: deduping an array?

I'm being a JavaScript dev at the moment, which is... interesting. My JS ain't bad, but I need to spend a lot of time with my nose in Google  / StackOverflow / MDN.

Here's something that I feel should be easier than I've made it:

// dedupe.js

abbccc = ["a", "b", "b", "c", "c", "c"];
abc = Object.keys(abbccc.reduce(function(obj, key){
    return obj;

console.log(abc); // ["a", "b", "c"]

I've had a google around and the "best" I've found is this answer on StackOverflow: "Remove Duplicates from JavaScript Array", but that all seems to be more complicated still.

How'd you go about it?


My colleague Amar came up with this one:

abc = abbccc.filter(function(elem, pos) {
    return abbccc.indexOf(elem) == pos;

Thats' quite a nice solution.