0

Is there a method that removes several identical/duplicate items from a JavaScript array like this:

var array = [55, 65, 55, 65, 55, 65, 55, 65, 55, 65];

With this array, for example, I am trying to remove all of the duplicates of 55 and 65 so that I am only left with [55, 65].

I've tried using splice() but that only removes by the position number, where I need something to remove all of the items of the same value.

dippas
  • 58,591
  • 15
  • 114
  • 126
gabrielwr
  • 198
  • 9

1 Answers1

2

You could filter the array and use a hash table for look-up.

var array = [55, 65, 55, 65, 55, 65, 55, 65, 55, 65, true, 'true'];

array = array.filter(function (a) {
    var key = typeof a + '|' + a;
    if (!this[key]) {
        this[key] = true;
        return true;
    }
}, Object.create(null));

document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392