556

I need to check a JavaScript array to see if there are any duplicate values. What's the easiest way to do this? I just need to find what the duplicated values are - I don't actually need their indexes or how many times they are duplicated.

I know I can loop through the array and check all the other values for a match, but it seems like there should be an easier way.

Similar question:

3
  • 30
    There seems to be years of confusion about what this question asks. I needed to know what elements in the array were duplicated: "I just need to find what the duplicated values are". The correct answer should NOT remove duplicates from the array. That's the inverse of what I wanted: a list of the duplicates, not a list of unique elements. Commented Feb 22, 2013 at 15:47
  • github.com/lodash/lodash/issues/4852#issuecomment-666366511 I would add this as an answer, but given the length of answers, it would never be seen Commented Jul 30, 2020 at 14:44
  • Christ, it seems no one knows how to read. Four pages of "answers" and most don't even answer the question (or even work!) Commented Apr 8 at 9:44

99 Answers 99

374

You could sort the array and then run through it and then see if the next (or previous) index is the same as the current. Assuming your sort algorithm is good, this should be less than O(n2):

const findDuplicates = (arr) => {
  let sorted_arr = arr.slice().sort(); // You can define the comparing function here. 
  // JS by default uses a crappy string compare.
  // (we use slice to clone the array so the
  // original array won't be modified)
  let results = [];
  for (let i = 0; i < sorted_arr.length - 1; i++) {
    if (sorted_arr[i + 1] == sorted_arr[i]) {
      results.push(sorted_arr[i]);
    }
  }
  return results;
}

let duplicatedArray = [9, 9, 111, 2, 3, 4, 4, 5, 7];
console.log(`The duplicates in ${duplicatedArray} are ${findDuplicates(duplicatedArray)}`);

In case, if you are to return as a function for duplicates. This is for similar type of case.

Reference: https://stackoverflow.com/a/57532964/8119511

22
  • 13
    "Assuming your sort algorithm is good, this should be less than O^2". Specifically, it could be O(n*log(n)).
    – ESRogs
    Commented May 8, 2009 at 17:20
  • 102
    This script doesn't work so well with more than 2 duplicates (e.g. arr = [9, 9, 9, 111, 2, 3, 3, 3, 4, 4, 5, 7];
    – Mottie
    Commented Oct 23, 2010 at 15:00
  • 7
    @swilliams I don't think those guidelines say anything about not using i++. Instead, they say not to write j = i + +j. Two different things IMHO. I think i += 1 is more confusing than the simple and beautiful i++ :) Commented Dec 23, 2010 at 14:31
  • 37
    -1 This answer is wrong on many levels. First of all var sorted_arr = arr.sort() is useless: arr.sort() mutates the original array (which is a problem in its own right). This also discards an element. (Run the code above. What happens to 9?) cc @dystroy A cleaner solution would be results = arr.filter(function(elem, pos) { return arr.indexOf(elem) == pos; }) Commented Jan 13, 2013 at 21:10
  • 26
    Everyone: the question asks to display the duplicate values, not to remove them. Please don't edit/break the code to try to make it do something it's not trying to do. The alert should show the values that are duplicated. Commented Feb 22, 2013 at 15:50
215

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: http://dreaminginjavascript.wordpress.com/2008/08/22/eliminating-duplicates/

12
  • 28
    That is good code, but unfortunately it doesn't do what I'm asking for. Commented May 8, 2009 at 17:59
  • 71
    The code above (which is mine--that's my blog) gets you pretty close. A small tweak and you're there. First of all, you can see if arr.length and out.length are the same. If they are the same, there are no duplicated elements. But you want a little more. If you want to "catch" the dupes as they happen, check to see if the length of the array increases after the obj[arr[i]]=0 line. Nifty, eh? :-) Thanks for the nice words, Raphael Montanaro.
    – Nosredna
    Commented May 8, 2009 at 22:25
  • 6
    @MarcoDemaio: Uh, no, why would the code not work with spaces? You can put whatever you like in a property name - just can't use the dot syntax to access ones with spaces (nor props with various other characters which would break parsing).
    – Gijs
    Commented Oct 11, 2011 at 10:29
  • 4
    @Gijs: +1 you are right. I didn't know it. But it still does not work when it's an array of objects. Commented Oct 16, 2011 at 12:19
  • 3
    This algorithm also has the side effect of returning a sorted array, which might not be what you want.
    – asymmetric
    Commented Jun 3, 2012 at 19:26
208

This is my answer from the duplicate thread (!):

When writing this entry 2014 - all examples were for-loops or jQuery. JavaScript has the perfect tools for this: sort, map and reduce.

Find duplicate items

var names = ['Mike', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Nancy', 'Carl']

const uniq = names
  .map((name) => {
    return {
      count: 1,
      name: name
    };
  })
  .reduce((result, b) => {
    result[b.name] = (result[b.name] || 0) + b.count;

    return result;
  }, {});
const duplicates = Object.keys(uniq).filter((a) => uniq[a] > 1);

console.log(duplicates); // [ 'Nancy' ]

More functional syntax:

@Dmytro-Laptin pointed out some code that can be removed. This is a more compact version of the same code. Using some ES6 tricks and higher-order functions:

const names = ['Mike', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Nancy', 'Carl'];
const count = names =>
  names.reduce((result, value) => ({ ...result,
    [value]: (result[value] || 0) + 1
  }), {}); // don't forget to initialize the accumulator
const duplicates = dict =>
  Object.keys(dict).filter((a) => dict[a] > 1);

console.log(count(names)); // { Mike: 1, Matt: 1, Nancy: 2, Adam: 1, Jenny: 1, Carl: 1 }
console.log(duplicates(count(names))); // [ 'Nancy' ]

3
  • @ChristianLandgren, where is 'dict' variable declared? maybe 'count' should be used instead? Commented Aug 18, 2016 at 14:30
  • the dict variable is a parameter to the fat-arrow function. It is shorthand for function(dict) { return Object.keys(dict) ... } Commented Aug 23, 2016 at 19:39
  • Note that this is not compatible with lower versions of IE due to the => syntax.
    – J0ANMM
    Commented Jul 1, 2019 at 18:47
174

UPDATED: Short one-liner to get the duplicates:

[1, 2, 2, 4, 3, 4].filter((e, i, a) => a.indexOf(e) !== i) // [2, 4]

To get the array without duplicates simply invert the condition:

[1, 2, 2, 4, 3, 4].filter((e, i, a) => a.indexOf(e) === i) // [1, 2, 3, 4]

Note that this answer’s main goal is to be short. If you need something performant for a big array, one possible solution is to sort your array first (if it is sortable) then do the following to get the same kind of results as above:

myHugeSortedArray.filter((e, i, a) => a[i-1] === e)

Here is an example for a 1 000 000 integers array:

const myHugeIntArrayWithDuplicates =
  [...Array(1_000_000).keys()]
  // adding two 0 and four 9 duplicates
  .fill(0, 2, 4).fill(9, 10, 14)

console.time("time")
console.log(
  myHugeIntArrayWithDuplicates
  // a possible sorting method for integers
  .sort((a, b) => a > b ? 1 : -1)
  .filter((e, i, a) => a[i-1] === e)
)
console.timeEnd("time")

On my AMD Ryzen 7 5700G dev machine it outputs:

[ 0, 0, 9, 9, 9, 9 ]
time: 22.738ms

As pointed out in the comments both the short solution and the performant solution will return an array with several time the same duplicate if it occurs more than once in the original array:

[1, 1, 1, 2, 2, 2, 2].filter((e, i, a) => a.indexOf(e) !== i) // [1, 1, 2, 2, 2]

If unique duplicates are wanted then a function like

function duplicates(arr) {
  return [...new Set(arr.filter((e, i, a) => a.indexOf(e) !== i))]
}

can be used so that duplicates([1, 1, 1, 2, 2, 2, 2]) returns [1, 2].


When all you need is to check that there are no duplicates as asked in this question you can use the every() method:

[1, 2, 3].every((e, i, a) => a.indexOf(e) === i) // true

[1, 2, 1].every((e, i, a) => a.indexOf(e) === i) // false

Note that every() doesn't work for IE 8 and below.

4
  • 7
    Remember: [2,2,2,2].filter((e, i, a) => a.indexOf(e) !== i) gives [2, 2, 2]
    – Wajahath
    Commented Apr 17, 2021 at 10:01
  • 6
    @Wajahath That's true, thanks for pointing that out. If unique duplicates are wanted then a function like f = arr => [...new Set(arr.filter((e, i, a) => a.indexOf(e) !== i))] can be used so that f([1, 1, 1, 2, 2, 2, 2]) returns [1, 2] Commented Apr 18, 2021 at 5:46
  • performance wise, this is really bad if you have like 1 000 000 entries
    – strix25
    Commented Oct 5, 2022 at 10:21
  • 1
    @strix25 that’s true, I added a similar solution that performs much better on a 1 000 000 sorted array. Commented Oct 7, 2022 at 9:09
77

Find duplicate values in an array

This should be one of the shortest ways to actually find duplicate values in an array. As specifically asked for by the OP, this does not remove duplicates but finds them.

var input = [1, 2, 3, 1, 3, 1];

var duplicates = input.reduce(function(acc, el, i, arr) {
  if (arr.indexOf(el) !== i && acc.indexOf(el) < 0) acc.push(el); return acc;
}, []);

document.write(duplicates); // = 1,3 (actual array == [1, 3])

// Or, using Sets (about 4 times faster)

var duplicates = Array.from(items.reduce((acc, v, i, arr) {
  return arr.indexOf(v) !== i ? acc.add(v) : acc;
}, new Set()))

This doesn't need sorting or any third party framework. It also doesn't need manual loops. It works with every value indexOf() (or to be clearer: the strict comparision operator) supports.

Because of reduce() and indexOf() it needs at least IE 9.

3
  • 12
    ES6 arrow/simple/pure version: const dupes = items.reduce((acc, v, i, arr) => arr.indexOf(v) !== i && acc.indexOf(v) === -1 ? acc.concat(v) : acc, [])
    – ZephDavies
    Commented Nov 29, 2018 at 14:56
  • if (arr.indexOf(el) !== i && !acc.includes(el) ) acc.push(el); return acc; works too Commented Oct 12, 2022 at 14:46
  • @ZephDavies You could also remove the negations and use includes instead of indexOf and rewrite it as follows: const dupes = items.reduce((acc, v, i, arr) => arr.indexOf(v) === i || acc.includes(v) ? acc : acc.concat(v), [])
    – Mina Luke
    Commented Aug 6 at 5:10
31

You can add this function, or tweak it and add it to Javascript's Array prototype:

Array.prototype.unique = function () {
    var r = new Array();
    o:for(var i = 0, n = this.length; i < n; i++)
    {
        for(var x = 0, y = r.length; x < y; x++)
        {
            if(r[x]==this[i])
            {
                alert('this is a DUPE!');
                continue o;
            }
        }
        r[r.length] = this[i];
    }
    return r;
}

var arr = [1,2,2,3,3,4,5,6,2,3,7,8,5,9];
var unique = arr.unique();
alert(unique);
3
  • This is the best solution, but be careful of adding it to the array prototype, since that will mess up IE if looping through the values. Commented Oct 12, 2012 at 6:59
  • @RoyTinker perl supports them too, but I had no idea javascript did
    – Luke H
    Commented Nov 14, 2012 at 17:13
  • 3
    Does not do what the OP asked for, return the duplicates.
    – RWC
    Commented Aug 18, 2017 at 12:10
28

UPDATED: The following uses an optimized combined strategy. It optimizes primitive lookups to benefit from hash O(1) lookup time (running unique on an array of primitives is O(n)). Object lookups are optimized by tagging objects with a unique id while iterating through so so identifying duplicate objects is also O(1) per item and O(n) for the whole list. The only exception is items that are frozen, but those are rare and a fallback is provided using an array and indexOf.

var unique = function(){
  var hasOwn = {}.hasOwnProperty,
      toString = {}.toString,
      uids = {};

  function uid(){
    var key = Math.random().toString(36).slice(2);
    return key in uids ? uid() : uids[key] = key;
  }

  function unique(array){
    var strings = {}, numbers = {}, others = {},
        tagged = [], failed = [],
        count = 0, i = array.length,
        item, type;

    var id = uid();

    while (i--) {
      item = array[i];
      type = typeof item;
      if (item == null || type !== 'object' && type !== 'function') {
        // primitive
        switch (type) {
          case 'string': strings[item] = true; break;
          case 'number': numbers[item] = true; break;
          default: others[item] = item; break;
        }
      } else {
        // object
        if (!hasOwn.call(item, id)) {
          try {
            item[id] = true;
            tagged[count++] = item;
          } catch (e){
            if (failed.indexOf(item) === -1)
              failed[failed.length] = item;
          }
        }
      }
    }

    // remove the tags
    while (count--)
      delete tagged[count][id];

    tagged = tagged.concat(failed);
    count = tagged.length;

    // append primitives to results
    for (i in strings)
      if (hasOwn.call(strings, i))
        tagged[count++] = i;

    for (i in numbers)
      if (hasOwn.call(numbers, i))
        tagged[count++] = +i;

    for (i in others)
      if (hasOwn.call(others, i))
        tagged[count++] = others[i];

    return tagged;
  }

  return unique;
}();

If you have ES6 Collections available, then there is a much simpler and significantly faster version. (shim for IE9+ and other browsers here: https://github.com/Benvie/ES6-Harmony-Collections-Shim)

function unique(array){
  var seen = new Set;
  return array.filter(function(item){
    if (!seen.has(item)) {
      seen.add(item);
      return true;
    }
  });
}
6
  • really? why answer a question which has been solved over 2 years ago?
    – Rene Pot
    Commented Oct 28, 2011 at 11:16
  • 3
    I was answering another question and apparently accidentally clicked on someone linking to this one, calling it a duplicate, and ended up cloning my answer and confusing the hell out of myself. I edit my stuff a lot.
    – user748221
    Commented Oct 28, 2011 at 11:19
  • stackoverflow.com/questions/7683845/…
    – user748221
    Commented Oct 28, 2011 at 11:19
  • 17
    I think it's nice with different solutions. It doesn't matter that the topic is old and solved since it's still possible to come up with different ways of doing this. It's a typical problem in computer science. Commented Nov 30, 2011 at 12:53
  • You might want to mention that this relies on ES5 Array methods that aren't implemented in IE < 9.
    – Tim Down
    Commented May 1, 2012 at 11:39
24
var a = ["a","a","b","c","c"];

a.filter(function(value,index,self){ return (self.indexOf(value) !== index )})
4
  • This seems to work, but you should probably include some text describing how it works. Commented Aug 20, 2015 at 15:27
  • 4
    Won't work if there are more 2 occurrences of a duplicate value.
    – vasa
    Commented Nov 3, 2015 at 0:37
  • 1
    This is elegant and simple. I love it. For those wanting to figure out how they work, I've created a gist showing how to show duplicates and eliminate duplicates. See here: gist.github.com/jbcoder/f1c616a32ee4d642691792eebdc4257b
    – Josh
    Commented Jul 22, 2016 at 17:40
  • @TheDIMMReaper for the second 'a' in array, inside filter function the index == 1, whereas self.indexOf('a') == 0 Commented Nov 16, 2018 at 13:40
23

This should get you what you want, Just the duplicates.

function find_duplicates(arr) {
  var len=arr.length,
      out=[],
      counts={};

  for (var i=0;i<len;i++) {
    var item = arr[i];
    counts[item] = counts[item] >= 1 ? counts[item] + 1 : 1;
    if (counts[item] === 2) {
      out.push(item);
    }
  }

  return out;
}

find_duplicates(['one',2,3,4,4,4,5,6,7,7,7,'pig','one']); // -> ['one',4,7] in no particular order.
0
23

Find non-unique values from 3 arrays (or more):

ES2015

//          🚩🚩  🚩   🚩             🚩 
var arr =  [1,2,2,3,3,4,5,6,2,3,7,8,5,22],
    arr2 = [1,2,511,12,50],
    arr3 = [22,0],
    merged,
    nonUnique;

// Combine all the arrays to a single one
merged = arr.concat(arr2, arr3)

// create a new (dirty) Array with only the non-unique items
nonUnique = merged.filter((item,i) => merged.includes(item, i+1))

// Cleanup - remove duplicate & empty items items 
nonUnique = [...new Set(nonUnique)]

console.log(nonUnique)


PRE-ES2015:

In the below example I chose to superimpose a unique method on top of the Array prototype, allowing access from everywhere and has more "declarative" syntax. I do not recommend this approach on large projects, since it might very well collide with another method with the same custom name.

Array.prototype.unique = function () {
    var arr = this.sort(), i=arr.length; // input must be sorted for this to work
    while(i--)
      arr[i] === arr[i-1] && arr.splice(i,1) // remove duplicate item
    return arr
}

Array.prototype.nonunique = function () {
    var arr = this.sort(), i=arr.length, res = []; // input must be sorted for this to work
    while(i--)
      arr[i] === arr[i-1] && (res.indexOf(arr[i]) == -1) && res.push(arr[i]) 
    return res
}

//          🚩🚩  🚩    🚩            🚩 
var arr =  [1,2,2,3,3,4,5,6,2,3,7,8,5,22],
    arr2 = [1,2,511,12,50],
    arr3 = [22,0],
    // merge all arrays & call custom Array Prototype - "unique"
    unique = arr.concat(arr2, arr3).unique(),
    nonunique = arr.concat(arr2, arr3).nonunique()

console.log(unique)     // [1,12,2,22,3,4,5,50,511,6,7,8]
console.log(nonunique)  // [1,12,2,22,3,4,5,50,511,6,7,8]

7
  • +1 because it's definitely more readable the code using Array.indexOf, but unfortunately it seems slower than using a simple nested loop. Even on browsers that implements Array.indexOf nayively like FF. Plz, Have a look at these tests I did here: jsperf.com/array-unique2 and let me know your thoughts. Commented Mar 4, 2011 at 16:41
  • @shekhardesigner - updated answer. "r" is the array you search in
    – vsync
    Commented Feb 20, 2014 at 14:40
  • @vsync I had to initialize, var r = []; to get your code working. And worked like charm.
    – absqueued
    Commented Feb 21, 2014 at 12:06
  • @shekhardesigner - I'm sorry for the mix, for the Array Prototype solution you don't need an r variable
    – vsync
    Commented Feb 21, 2014 at 12:40
  • 2
    Does not do what the OP asked for, return the duplicates.
    – RWC
    Commented Aug 18, 2017 at 12:16
14

The simplest and quickest way is to use the Set object:

const numbers = [1, 2, 3, 2, 4, 5, 5, 6];

const set = new Set(numbers);

const duplicates = numbers.filter(item => {
    if (set.has(item)) {
        set.delete(item);
        return false;
    } else {
        return true;
    }
});

// OR more concisely

const duplicates = numbers.filter(item => !set.delete(item));

console.log(duplicates);
// [ 2, 5 ]
3
  • Good clear algorithm. By the way, this reports triplicate elements twice, which may well be desirable.
    – Bob Stein
    Commented Dec 22, 2021 at 21:11
  • An improvement on this would be item => !set.delete(item), as Set.delete() return false if the item was not in the set.
    – nebkat
    Commented Nov 8, 2022 at 12:16
  • @nebkat Set.delete() returns false if the item was not in the array and true if it was. We want the opposite of that, so we invert it. That makes sense. It just feels a little confusing to read the concise version because two things are happening: it's checking for the item in the set, and deleting the item from the set. I'm just asking for clarification really, thank you.
    – TopMarx
    Commented Feb 8 at 0:44
13

using underscore.js

function hasDuplicate(arr){
    return (arr.length != _.uniq(arr).length);
}
0
9

This is my proposal (ES6):

let a = [1, 2, 3, 4, 2, 2, 4, 1, 5, 6]
let b = [...new Set(a.sort().filter((o, i) => o !== undefined && a[i + 1] !== undefined && o === a[i + 1]))]

// b is now [1, 2, 4]
2
  • 1
    This will report that a single occurrence of undefined is a duplicate. Commented Dec 2, 2018 at 7:49
  • 1
    updated solution based on the comment (forgot to mention it earlier)
    – lukaszkups
    Commented Jan 5, 2021 at 14:22
9

Here's the simplest solution I could think of:

const arr = [-1, 2, 2, 2, 0, 0, 0, 500, -1, 'a', 'a', 'a']

const filtered = arr.filter((el, index) => arr.indexOf(el) !== index)
// => filtered = [ 2, 2, 0, 0, -1, 'a', 'a' ]

const duplicates = [...new Set(filtered)]

console.log(duplicates)
// => [ 2, 0, -1, 'a' ]

That's it.

Note:

  1. It works with any numbers including 0, strings and negative numbers e.g. -1 - Related question: Get all unique values in a JavaScript array (remove duplicates)

  2. The original array arr is preserved (filter returns the new array instead of modifying the original)

  3. The filtered array contains all duplicates; it can also contain more than 1 same value (e.g. our filtered array here is [ 2, 2, 0, 0, -1, 'a', 'a' ])

  4. If you want to get only values that are duplicated (you don't want to have multiple duplicates with the same value) you can use [...new Set(filtered)] (ES6 has an object Set which can store only unique values)

Hope this helps.

8

Here is mine simple and one line solution.

It searches not unique elements first, then makes found array unique with the use of Set.

So we have array of duplicates in the end.

var array = [1, 2, 2, 3, 3, 4, 5, 6, 2, 3, 7, 8, 5, 22, 1, 2, 511, 12, 50, 22];

console.log([...new Set(
  array.filter((value, index, self) => self.indexOf(value) !== index))]
);

7

Shortest vanilla JS:

[1,1,2,2,2,3].filter((v,i,a) => a.indexOf(v) !== i) // [1, 2, 2]
2
  • and if you need result without duplication new Set(result) will get rid of them Commented Oct 17, 2020 at 10:40
  • I like this solution sooo much! Commented Jun 6, 2022 at 20:38
7

one liner simple way

var arr = [9,1,2,4,3,4,9]
console.log(arr.filter((ele,indx)=>indx!==arr.indexOf(ele))) //get the duplicates
console.log(arr.filter((ele,indx)=>indx===arr.indexOf(ele))) //remove the duplicates

3
  • what does indx! do for the first example? Commented Mar 25, 2019 at 17:51
  • 2
    @saylestyler Hehe, this means indx !== ... - strict inequality. Commented Nov 18, 2019 at 12:37
  • only adding for array of objects result.filter((ele,indx) => indx !== result.map(e => e.name).indexOf(ele.name));
    – x-magix
    Commented Dec 14, 2019 at 20:18
6
var a = [324,3,32,5,52,2100,1,20,2,3,3,2,2,2,1,1,1].sort();
a.filter(function(v,i,o){return i&&v!==o[i-1]?v:0;});

or when added to the prototyp.chain of Array

//copy and paste: without error handling
Array.prototype.unique = 
   function(){return this.sort().filter(function(v,i,o){return i&&v!==o[i-1]?v:0;});}

See here: https://gist.github.com/1305056

2
  • 1
    The filter function should return true or false, not the element itself. Filtering an array containing 0's would not have returned them.
    – mflodin
    Commented Jan 9, 2012 at 23:43
  • Also, I assume the i&& is for avoiding going out of bounds of the array, but it also means that the first element in the sorted array will not be included. In your example there is no 1 in the resulting array. I.e. return i&&v!==o[i-1]?v:0; should be return v!==o[i-1];
    – mflodin
    Commented Jan 10, 2012 at 0:48
6

Fast and elegant way using es6 object destructuring and reduce

It runs in O(n) (1 iteration over the array) and doesn't repeat values that appear more than 2 times

const arr = ['hi', 'hi', 'hi', 'bye', 'bye', 'asd']
const {
  dup
} = arr.reduce(
  (acc, curr) => {
    acc.items[curr] = acc.items[curr] ? acc.items[curr] += 1 : 1
    if (acc.items[curr] === 2) acc.dup.push(curr)
    return acc
  }, {
    items: {},
    dup: []
  },
)

console.log(dup)
// ['hi', 'bye']

5

You can use filter method and indexOf() to get all the duplicate values

function duplicate(arr) {
    return duplicateArray = arr.filter((item, index) => arr.indexOf(item) !== index) 
}

arr.indexOf(item) will always return the first index at which a given element can be found

4

The following function (a variation of the eliminateDuplicates function already mentioned) seems to do the trick, returning test2,1,7,5 for the input ["test", "test2", "test2", 1, 1, 1, 2, 3, 4, 5, 6, 7, 7, 10, 22, 43, 1, 5, 8]

Note that the problem is stranger in JavaScript than in most other languages, because a JavaScript array can hold just about anything. Note that solutions that use sorting might need to provide an appropriate sorting function--I haven't tried that route yet.

This particular implementation works for (at least) strings and numbers.

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

    for (i=0;i<len;i++) {
        if (obj[arr[i]] != null) {
            if (!obj[arr[i]]) {
                out.push(arr[i]);
                obj[arr[i]] = 1;
            }
        } else {
            obj[arr[i]] = 0;            
        }
    }
    return out;
}
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] );
    });
1
  • I like this simple solution. If you want the duplicates, though, you need to first find those duplicates, and then make the duplicate list unique. [ 0, 4, 5, 5, 5, 2, 1, 3, 1, 1, 2, 1, 3 ].sort().filter( function(me,i,arr){ return (i!==0) && ( me == arr[i-1] ); }).filter( function(me,i,arr){ return (i===0) || ( me !== arr[i-1] ); });
    – Greg
    Commented Jul 24, 2019 at 18:37
4

Here is a very light and easy way:

var codes = dc_1.split(',');
var i = codes.length;
while (i--) {
  if (codes.indexOf(codes[i]) != i) {
    codes.splice(i,1);
  }
}
1
  • Best answer. And if user want duplicate elements array , for this i updated @brandon code var i = codes .length; var duplicate = []; while (i--) { if (codes .indexOf(codes [i]) != i) { if(duplicate.indexOf(codes [i]) === -1){ duplicate.push(arr[i]); } codes.splice(i,1); } } Commented Aug 18, 2019 at 7:18
4

ES6 offers the Set data structure which is basically an array that doesn't accept duplicates. With the Set data structure, there's a very easy way to find duplicates in an array (using only one loop).

Here's my code

function findDuplicate(arr) {
var set = new Set();
var duplicates = new Set();
  for (let i = 0; i< arr.length; i++) {
     var size = set.size;
     set.add(arr[i]);
     if (set.size === size) {
         duplicates.add(arr[i]);
     }
  }
 return duplicates;
}
1
  • 1
    This is a great solution. I'm surprised it hasn't received more upvotes!
    – Jack_Hu
    Commented Jun 5, 2022 at 17:36
4

With ES6 (or using Babel or Typescipt) you can simply do:

var duplicates = myArray.filter(i => myArray.filter(ii => ii === i).length > 1);

https://es6console.com/j58euhbt/

1
  • I came to the same syntax, independently, and was just about to add it as a solution when I found this one. It probably isn't the most economical, but it is simple.
    – nize
    Commented May 7, 2018 at 8:50
4

Simple code with ES6 syntax (return sorted array of duplicates):

let duplicates = a => {d=[]; a.sort((a,b) => a-b).reduce((a,b)=>{a==b&&!d.includes(a)&&d.push(a); return b}); return d};

How to use:

duplicates([1,2,3,10,10,2,3,3,10]);
1
  • 2
    .filter() would be much simpler
    – Franc
    Commented May 7, 2018 at 13:08
4

I have just figured out a simple way to achieve this using an Array filter

    var list = [9, 9, 111, 2, 3, 4, 4, 5, 7];
    
    // Filter 1: to find all duplicates elements
    var duplicates = list.filter(function(value,index,self) {
       return self.indexOf(value) !== self.lastIndexOf(value) && self.indexOf(value) === index;
    });
    
    console.log(duplicates);

4

This answer might also be helpful, it leverages js reduce operator/method to remove duplicates from array.

const result = [1, 2, 2, 3, 3, 3, 3].reduce((x, y) => x.includes(y) ? x : [...x, y], []);

console.log(result);

1
  • 6
    we can now just do new Set([1, 2, 2, 3, 3, 3, 3]) to remove duplicates
    – kimbaudi
    Commented Nov 20, 2019 at 0:05
4

Higher ranked answers have a few inherent issues including the use of legacy javascript, incorrect ordering or with only support for 2 duplicated items.

Here's a modern solution which fixes those problems:

const arrayNonUniq = array => {
    if (!Array.isArray(array)) {
        throw new TypeError("An array must be provided!")
    }

    return array.filter((value, index) => array.indexOf(value) === index && array.lastIndexOf(value) !== index)
}

arrayNonUniq([1, 1, 2, 3, 3])
//=> [1, 3]

arrayNonUniq(["foo", "foo", "bar", "foo"])
//=> ['foo']

You can also use the npm package array-non-uniq.

3

var arr = [2, 1, 2, 2, 4, 4, 2, 5];

function returnDuplicates(arr) {
  return arr.reduce(function(dupes, val, i) {
    if (arr.indexOf(val) !== i && dupes.indexOf(val) === -1) {
      dupes.push(val);
    }
    return dupes;
  }, []);
}

alert(returnDuplicates(arr));

This function avoids the sorting step and uses the reduce() method to push duplicates to a new array if it doesn't already exist in it.

Not the answer you're looking for? Browse other questions tagged or ask your own question.