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

Viewed 825158

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:

96 Answers

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

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/

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);

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.

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);
    } else {
        return item;
    }
});

console.log(duplicates);
// [ 2, 5 ]

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.

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))]
);

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]

Shortest vanilla JS:

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

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']

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

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);

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.

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;
}

Following logic will be easier and faster

// @Param:data:Array that is the source 
// @Return : Array that have the duplicate entries
findDuplicates(data: Array<any>): Array<any> {
        return Array.from(new Set(data)).filter((value) => data.indexOf(value) !== data.lastIndexOf(value));
      }

Advantages :

  1. Single line :-P
  2. All inbuilt data structure helping in improving the efficiency
  3. Faster

Description of Logic :

  1. Converting to set to remove all duplicates
  2. Iterating through the set values
  3. With each set value check in the source array for the condition "values first index is not equal to the last index" == > Then inferred as duplicate else it is 'unique'

Note: map() and filter() methods are efficient and faster.

Just to add some theory to the above.

Finding duplicates has a lower bound of O(n*log(n) in the comparison model. SO theoretically, you cannot do any better than first sorting then going through the list sequentially removing any duplicates you find.

If you want to find the duplicates in linear (O(n)) expected time, you could hash each element of the list; if there is a collision, remove/label it as a duplicate, and continue.

There is a really simple way to solve this. If you use the newish 'Set' javascript command. Set can take an array as input and output a new 'Set' that only contains unique values. Then by comparing the length of the array and the 'size' property of the set you can see if they differ. If they differ it must be due to a duplicate entry.

var array1 = ['value1','value2','value3','value1']; // contains duplicates
var array2 = ['value1','value2','value3','value4']; // unique values

console.log('array1 contains duplicates = ' + containsDuplicates(array1));
console.log('array2 contains duplicates = ' + containsDuplicates(array2));


function containsDuplicates(passedArray) {
  let mySet = new Set(passedArray);
  if (mySet.size !== passedArray.length) {
    return true;
  }
  return false;
}

If you run the above snippet you will get this output.

array1 contains duplicates = true

array2 contains duplicates = false

this is the simplest way to find the duplicated elements with ES6 syntax

const arr =[1,2,3,3,21,3, 21,34]
const duplicates = Array.from(new Set(arr.filter((eg, i, ar)=> i !==ar.indexOf(eg))))
console.log(duplicates)

This is one of the simple ES5 solution I could think of -

function duplicates(arr) {
  var duplicatesArr = [],
      uniqueObj = {};

  for (var i = 0; i < arr.length; i++) {
    if( uniqueObj.hasOwnProperty(arr[i]) && duplicatesArr.indexOf( arr[i] ) === -1) {
      duplicatesArr.push( arr[i] );
    }
    else {
      uniqueObj[ arr[i] ] = true;
    }
  }

  return duplicatesArr;
}
/* Input Arr: [1,1,2,2,2,1,3,4,5,3] */
/* OutPut Arr: [1,2,3] */

//find duplicates:
//sort, then reduce - concat values equal previous element, skip others

//input
var a = [1, 2, 3, 1, 2, 1, 2]

//short version:
var duplicates = a.sort().reduce((d, v, i, a) => i && v === a[i - 1] ? d.concat(v) : d, [])
console.log(duplicates); //[1, 1, 2, 2]

//readable version:
var duplicates = a.sort().reduce((output, element, index, input) => {
  if ((index > 0) && (element === input[index - 1]))
    return output.concat(element)
  return output
}, [])
console.log(duplicates); //[1, 1, 2, 2]

  1. Printing duplicate values

 var arr = [1,2,3,4,13,2,3,4,3,4];

    // non_unique Printing 
    function nonUnique(arr){
    var result = [];
    for(var i =0;i<arr.length;i++){
        if(arr.indexOf(arr[i],i+1) > -1){
            result.push(arr[i]);
        }
    }
    console.log(result);
    }nonUnique(arr);

    // unique Printing
    function uniqueDuplicateVal(arr){
       var result = [];
       for(var i =0;i<arr.length;i++){
        if(arr.indexOf(arr[i],i+1) > -1){
          if(result.indexOf(arr[i]) === -1]){
             result.push(arr[i]);
          }
        }
       }    
    }
    uniqueDuplicateVal(arr)

This should be one of the shortest and easiest ways to actually find duplicate values in an array.

var arr = [1,2,3,4,5,6,7,8,1,2,3,4,5,3,3,4];
var data = arr.filter(function(item,index,arr){
  return arr.indexOf(item) != arr.lastIndexOf(item) && arr.indexOf(item) == index;
})

console.log(data );

This is most efficient way i can think of as doesn't include Array.indexOf() or Array.lastIndexOf() which have complexity of O(n) and using inside any loop of complexity O(n) will make complete complexity O(n^2).

My first loop have complexity of O(n/2) or O((n/2) + 1), as complexity of search in hash is O(1). The second loop worst complexity when there's no duplicate in array is O(n) and best complexity when every element have a duplicate is O(n/2).

function duplicates(arr) {
  let duplicates = [],
      d = {},
      i = 0,
      j = arr.length - 1;

  // Complexity O(n/2)
  while (i <= j) {
    if (i === j)
      d[arr[i]] ? d[arr[i]] += 1 : d[arr[i]] = 1;  // Complexity O(1)
    else {
      d[arr[i]] ? d[arr[i]] += 1 : d[arr[i]] = 1;  // Complexity O(1)
      d[arr[j]] ? d[arr[j]] += 1 : d[arr[j]] = 1;  // Complexity O(1)
    }

    ++i;
    --j;
  }

  // Worst complexity O(n), best complexity O(n/2)
  for (let k in d) {
    if (d[k] > 1)
      duplicates.push(k);
  }

  return duplicates;

}

console.log(duplicates([5,6,4,9,2,3,5,3,4,1,5,4,9]));
console.log(duplicates([2,3,4,5,4,3,4]));
console.log(duplicates([4,5,2,9]));
console.log(duplicates([4,5,2,9,2,5,9,4]));

Magic

a.filter(( t={}, e=>!(1-(t[e]=++t[e]|0)) )) 

O(n) performance; we assume your array is in a and it contains elements that can be cast .toString() in unique way (which is done implicity by JS in t[e]) e.g numbers=[4,5,4], strings=["aa","bb","aa"], arraysNum=[[1,2,3], [43,2,3],[1,2,3]]. Explanation here, unique values here

var a1 = [[2, 17], [2, 17], [2, 17], [1, 12], [5, 9], [1, 12], [6, 2], [1, 12]];
var a2 = ['Mike', 'Adam','Matt', 'Nancy', 'Adam', 'Jenny', 'Nancy', 'Carl'];
var a3 = [5,6,4,9,2,3,5,3,4,1,5,4,9];

let nd = (a) => a.filter((t={},e=>!(1-(t[e]=++t[e]|0)))) 


// Print
let c= x => console.log(JSON.stringify(x));             
c( nd(a1) );
c( nd(a2) );
c( nd(a3) );

This is a single loop approach with a hash table for counting the elements and filter the array if the count is 2, because it returns the first found duplicate.

Advantage:

  • single loop
  • uses an object for counting in a closure

var array = [5, 0, 2, 1, 2, 3, 3, 4, 4, 8, 6, 7, 9, 4],
    duplicates = array.filter((h => v => (h[v] = (h[v] || 0) + 1) === 2)({}));
    
console.log(duplicates);

You can make use of the sort, filter and sets to do that.

var numbers = [1,2,3,4,5,6,7,8,1,2,3,4,5,3,3,4];
var numbersSorted = numbers.sort();
let result = numbers.filter((e, i) => numbers[i] == numbers[i+1]);
result = [...new Set(result)];
console.log(result);

Based on @bluemoon but shorter, returns all duplicates exactly once!

function checkDuplicateKeys(arr) {
    const counts = {}
    return arr.filter((item) => {
        counts[item] = counts[item] || 1
        if (counts[item]++ === 2) return true
    })
}

// [1,2,2,2,2,2,2] => [1,2]
// ['dog', 'dog', 'cat'] => ['dog']

const names = [
  "Alex",
  "Matt",
  12,
  "You",
  "Me",
  12,
  "Carol",
  "Bike",
  "Carol",
];

const count = (names) =>
  names.reduce((a, b) => ({ ...a, [b]: (a[b] || 0) + 1 }), {});

let obj = count(names);
let objectKeys = Object.keys(obj);

let repetitiveElements = [];
let answer = objectKeys.map((value) => {
  if (obj[value] > 1) {
    return repetitiveElements.push(value);
  }
});
console.log(repetitiveElements); 

There are so many answers already, but unfortunately some are too long, some are short but too cryptic for me while others are beyond my scope of knowledge... I really like this solution that I've come up with, though. Hope it's still helpful for some!

Even though the original post says he/she doesn't actually need the duplicates' indexes or how many times they are duplicated, I think it's still clearest to have 'em counted.

Codes with notes.

function findDuplicates(array, count = {}) {
  // with count declared in the parameter, initialized as an empty object, 
  // it can store the counts of all elements in array  
  
  // using the forEach loop to iterate through the input array, 
  // also using the conditional ternary operators 
  // (works just like a normal if-else statement, but just a bit cleaner)
  // we can store all occurrences of each element from array in count
  array.forEach(el => count[el] ? count[el]++ : count[el] = 1)
  
  // using Object.keys, we get an array of all keys from count (all numbers) 
  // (sorted as well, though of no specific importance here)
  // using filter to find all elements with a count (value) > 1 (duplicates!)
  return Object.keys(count).filter(key => count[key] > 1);
}

Just the codes (with test cases).

function findDuplicates(array, count = {}) {
  array.forEach(el => count[el] ? count[el]++ : count[el] = 1);
  return Object.keys(count).filter(key => count[key] > 1);
}

let arr1 = [9, 9, 111, 2, 3, 4, 4, 5, 7];
let arr2 = [1,6,7,3,6,8,1,3,4,5,1,7,2,6];
console.log(findDuplicates(arr1)); // => ['4', '9']
console.log(findDuplicates(arr2)); // => ['1', '3', '6', '7']

It's actually a shame that this question has so many wrong answers or answers which need a lot of extra memory like a Set. Clean and simple solution:

function findDuplicates<T>(arr: Array<T>): T[] {
  //If the array has less than 2 elements there are no duplicates
  const n = arr.length;
  if (n < 2)
    return [];
  
  const sorted = arr.sort();
  const result = [];

  //Head
  if (sorted[0] === sorted[1])
    result.push(sorted[0]);

  //Inner (Head :: Inner :: Tail)
  for (let i = 1; i < n-1; i++) {
    const elem = sorted[i];
    if (elem === sorted[i - 1] || elem === sorted[i+1])
      result.push(elem)
  }

  //Tail
  if (sorted[n - 1] == sorted[n - 2])
    result.push(sorted[n - 1]);

  return result;
}

console.dir(findDuplicates(['a', 'a', 'b', 'b']));
console.dir(findDuplicates(['a', 'b']));
console.dir(findDuplicates(['a', 'a', 'a']));
console.dir(findDuplicates(['a']));
console.dir(findDuplicates([]));

The shortest way to remove duplicates is by using Set and Spread syntax

const remove = (array) => [...new Set(array)];
console.log(remove([1,1,2,2,3]); //1,2,3

The Prototype library has a uniq function, which returns the array without the dupes. That's only half of the work though.

/* The indexOf method of the Array object is useful for comparing array items. IE is the only major browser that does not natively support it, but it is easy to implement: */

Array.prototype.indexOf= Array.prototype.indexOf || function(what, i){
    i= i || 0;
    var L= this.length;
    while(i<L){
        if(this[i]=== what) return i;
        ++i;
    }
    return -1;
}

function getarrayduplicates(arg){
    var itm, A= arg.slice(0, arg.length), dups= [];
    while(A.length){
        itm= A.shift();
        if(A.indexOf(itm)!= -1 && dups.indexOf(itm)== -1){
            dups[dups.length]= itm;
        }
    }
    return dups;
}

var a1= [1, 22, 3, 2, 2, 3, 3, 4, 1, 22, 7, 8, 9];

alert(getarrayduplicates(a1));

For very large arrays, it can be faster to remove the duplicates from the array as they are found, so that they will not be looked at again:

function getarrayduplicates(arg){
    var itm, A= arg.slice(0, arg.length), dups= [];
    while(A.length){
        itm= A.shift();
        if(A.indexOf(itm)!= -1){
            dups[dups.length]= itm;
            while(A.indexOf(itm)!= -1){
                A.splice(A.indexOf(itm), 1);
            }
        }
    }
    return dups;
}

Here is one implemented using sort() and JSON.stringify()

https://gist.github.com/korczis/7598657

function removeDuplicates(vals) {
    var res = [];
    var tmp = vals.sort();

    for (var i = 0; i < tmp.length; i++) {
        res.push(tmp[i]);
                    while (JSON.stringify(tmp[i]) == JSON.stringify(tmp[i + 1])) {
            i++;
        }
    }

    return res;
}
console.log(removeDuplicates([1,2,3,4,5,4,3,3,2,1,]));

This is how I implemented it with map. It should run in O(n) time and should kinda be easy to gasp.

    var first_array=[1,1,2,3,4,4,5,6];
    var find_dup=new Map;

    for (const iterator of first_array) {
            // if present value++
            if(find_dup.has(iterator)){ 
                find_dup.set(iterator,find_dup.get(iterator)+1); 
            }else{
            // else add it
                find_dup.set(iterator,1);
            }
        }
    console.log(find_dup.get(2));

Then you can find_dup.get(key) to find if it has duplicates (it should give > 1).

Returns duplicates and preserves data type.

With O(4n) performance

const dupes = arr => {
  const map = arr.reduce((map, curr) => {
    return (map.set(curr, (map.get(curr) || 0) + 1), map)
  }, new Map());

  return Array.from(map).filter(([key, val])=> val > 1).map(([key, val]) => key)
}

With O(2n) performance

const dupes = arr => {
  const map = arr.reduce((map, curr) => {
    return (map.set(curr, (map.get(curr) || 0) + 1), map)
  }, new Map());

  const dupes_ = [];
  for (let [key, val] of map.entries()) {
    if (val > 1) dupes_.push(key);
  }
  return dupes_;
}

Simplest way to fetch duplicates/repeated values from array/string :

function getDuplicates(param) {
  var duplicates = {}

  for (var i = 0; i < param.length; i++) {
    var char = param[i]
    if (duplicates[char]) {
      duplicates[char]++
    } else {
      duplicates[char] = 1
    }
  }
  return duplicates
}

console.log(getDuplicates("aeiouaeiou"));
console.log(getDuplicates(["a", "e", "i", "o", "u", "a", "e"]));
console.log(getDuplicates([1, 2, 3, 4, 5, 1, 1, 2, 3]));

This will return duplicates from an Array as an Array of duplicates.

    const duplicates = function(arr) {
      // let try moving in pairs.. maybe that will work
      let dups = new Set(),
          r = []
      arr.sort()
      arr.reduce((pv, cv) => {
        if (pv === cv) {
          dups.add(pv)
        }
        return cv
      })
      for (let m of dups.values()) {
        r.push(m)
      }
      return r
    }
    
    console.log(duplicates([1,3,5,6,7,4,4,5,1,4,6,3,8,9,5,0]))

Very simple way:

function getDuplicateValues(someArray) {
 const duplicateValues = new Set([])
 const check = new Set([])
 someArray.forEach(v => {
  if (check.has(v)) {
   duplicateValues.add(v)
  } else {
   check.add(v)
  }
 })
 return Array.from(duplicateValues);
}

const result = getDuplicateValues(['coffee', 'soda', 'water', 'juice', 'water', 'water', 'coffee'])

repeated_values.textContent = JSON.stringify(result, null, '  ')
<pre id="repeated_values"></pre>

The accepted answer is the most perfect one but as some users has pointed that for cases where an element is repeated more than 2 times it will gives us the array with repeated elements:

This solution covers that scenarios too::

const peoples = [
  {id: 1, name:"Arjun"},
  {id: 2, name:"quinze"},
  {id: 3, name:"catorze"},
  {id: 1, name:"Arjun"},
  {id: 4, name:"dezesseis"},
  {id: 1, name:"Arjun"},
  {id: 2, name:"quinze"},
  {id: 3, name:"catorzee"}
]


function repeated(ppl){

  const newppl = ppl.slice().sort((a,b) => a.id -b.id);

  let rept = [];
  for(let i = 0; i < newppl.length-1 ; i++){
    if (newppl[i+1].id == newppl[i].id){
      rept.push(newppl[i+1]);
    }
  }

  return [...new Set(rept.map(el => el.id))].map(rid => 
    rept.find(el => el.id === rid)
  );

}

repeated(peoples);
[1, 2, 2, 3, 3, 4, 5, 6, 2, 3, 50, 8, 5, 22, 1, 2, 511, 12, 50, 22].reduce(function (total, currentValue, currentIndex, arr) {
    if (total.indexOf(currentValue) === -1 && arr.indexOf(currentValue) !== currentIndex) 
        total.push(currentValue);
    return total;
}, [])

You can use the following code to get the duplicate elements in a given array:

let name = ['satya', 'amit', 'aditya', 'abhay', 'satya', 'amit'];
let dup = [];
let uniq = [];
name.forEach((item, index) => {
  if(!uniq.includes(item)) {
    uniq[index] = item;
  }
  if (name.indexOf(item, index + 1) != -1) {
    dup[index] = item;
  }
})

I just need to find what the duplicated values are - I don't actually need their indexes or how many times they are duplicated.

A fun and simple task with many hard-to-read answers...

Typescript

function getDuplicatedItems<T>(someArray: T[]): T[] {
    // create a set to iterate through (we only need to check each value once)
    const itemSet = new Set<T>(someArray);

    // from that Set, we check if any of the items are duplicated in someArray
    const duplicatedItems = [...itemSet].filter(
        (item) => someArray.indexOf(item) !== someArray.lastIndexOf(item)
    );

    return duplicatedItems;
}

JavaScript

function getDuplicatedItems(someArray) {
    // check for misuse if desired
    // if (!Array.isArray(someArray)) {
    //     throw new TypeError(`getDuplicatedItems requires an Array type, received ${typeof someArray} type.`);
    // }
    const itemSet = new Set(someArray);
    const duplicatedItems = [...itemSet].filter(
        (item) => someArray.indexOf(item) !== someArray.lastIndexOf(item)
    );
    return duplicatedItems;
}

You can proceed by comparing index:

function getDuplicate(array) {
    return array.filter((value, index) => array.value !== index)
}

We will use Javascript ES6 Functionality to do magic!

var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];
const filtered = arr.filter((value, index) => {
 return arr.indexOf(value) >= index;
});

console.log(filtered);

https://jsfiddle.net/97Lxupnz/

var arr = ['a','b','c','a'];

arr.filter( (item , index ) => {  
console.log(item , index , arr.indexOf(item) , arr.indexOf( item ) == index);
return index == arr.indexOf(item)
 } );

enter image description here

var array = ['a', 'b', 'c', 'a'];

function unique(array) {
    var unique_arr = [];
    array.forEach(function(i, e) {
        if (unique_arr.indexOf(i)===-1) unique_arr.push(i);
    });
    return unique_arr;
}
console.log(unique(array));

This was asked me in an interview, My answer is,

List<int> getDublicates(List<int> x)
{
   List<int> result = new List<int>();
   while (x.Count>0)
   {
      int d = x[0];
      x.Remove(x[0]);
      if (x.Contains(d)) 
      result.Add(d);
   }
   return result;
}

it have good performance

Related