Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to return duplicate elements in an Array

Here is the way I am using to return duplicate elements.. But I am facing most dangerous performance issues like browser close etc when my array have large number of items with long texts..

var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];
var sorted_arr = arr.sort();
var results = [];
for (var i = 0; i < arr.length - 1; i++) {
  if (sorted_arr[i + 1] == sorted_arr[i]) {
     results.push(sorted_arr[i]);
  }
}
alert(results);

Please suggest me a best way of doing this

like image 818
Exception Avatar asked Nov 29 '11 16:11

Exception


People also ask

How do you find duplicate values in an array?

function checkIfArrayIsUnique(myArray) { for (var i = 0; i < myArray. length; i++) { for (var j = 0; j < myArray. length; j++) { if (i != j) { if (myArray[i] == myArray[j]) { return true; // means there are duplicate values } } } } return false; // means there are no duplicate values. }


2 Answers

i don't get exactly what you want, but if you need to return duplicates you could use a cache object. this works with number or string or whatever.

var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];
var cache = {};
var results = [];
for (var i = 0, len = arr.length; i < len; i++) {
  if(cache[arr[i]] === true){
      results.push(arr[i]);
   }else{
       cache[arr[i]] = true;
   }

}
console.log(results);//returns an array with 9 and 4

Of course you can do other things like deleting multiple items etc. etc.

EDIT - i've written a blog entry on how to remove duplicates from an array

like image 125
Nicola Peluchetti Avatar answered Nov 08 '22 03:11

Nicola Peluchetti


If you have array filter, you also have indexOf and lastIndexOf, and you can return the duplicates without doing the sort.

var results, arr= [9, 9, 111, 2, 3, 4, 4, 5, 4, 7];

if(arr.filter){
    results= arr.filter(function(itm, i){
        return arr.lastIndexOf(itm)== i && arr.indexOf(itm)!= i;
    });
}

else// use your loop method

alert(results)

/*  returned value: (Array)
9,4
*/
like image 38
kennebec Avatar answered Nov 08 '22 02:11

kennebec