Alex Rivera | Logout

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

Asked 2009-05-08T16:48:31.213
565

I need to check a JavaScript array to see if there are any duplicate values. How can I do this? I just need to find what the duplicated values are, and I don't actually need their indexes or how many times they are duplicated.

Edit
Report

4 Answers

216

If you want to elimate the duplicates, try this great solution:

function eliminateDuplicates(arr) {
  var i,
      len = arr.length,
      out = [],
      obj = {};

  for (i = 0; i < len; i++) {
    obj[arr[i]] = 0;
  }
  for (i in obj) {
    out.push(i);
  }
  return out;
}

console.log(eliminateDuplicates([1,6,7,3,6,8,1,3,4,5,1,7,2,6]))

Source: Eliminating Duplicates

answered 2009-05-08T17:05:48.910
4

ES5 only (i.e., it needs a filter() polyfill for IE8 and below):

var arrayToFilter = [ 4, 5, 5, 5, 2, 1, 3, 1, 1, 2, 1, 3 ];

arrayToFilter.
    sort().
    filter( function(me,i,arr){
       return (i===0) || ( me !== arr[i-1] );
    });
answered 2012-07-31T09:45:04.963
1

Yet another way by using underscore. Numbers is the source array and dupes has possible duplicate values:

var itemcounts = _.countBy(numbers, function (n) { return n; });
var dupes = _.reduce(itemcounts, function (memo, item, idx) {
    if (item > 1)
        memo.push(idx);
    return memo;
}, []);
answered 2013-04-07T21:29:06.063
0

Here is the one of methods to avoid duplicates into JavaScript array...and it supports for strings and numbers:

 var unique = function(origArr) {
    var newArray = [],
        origLen = origArr.length,
        found,
        x = 0; y = 0;
        
    for ( x = 0; x < origLen; x++ ) {
        found = undefined;
        for ( y = 0; y < newArray.length; y++ ) {
            if ( origArr[x] === newArray[y] ) found = true;
        }
        if ( !found) newArray.push( origArr[x] );    
    }
   return newArray;
}

Check this fiddle.

answered 2013-02-04T09:00:40.423

Your Answer