Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fastest way to detect if duplicate entry exists in javascript array?

var arr = ['test0','test2','test0'];

Like the above,there are two identical entries with value "test0",how to check it most efficiently?

like image 963
Mask Avatar asked Oct 14 '09 07:10

Mask


People also ask

How do you check if there are duplicates in an array JavaScript?

Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.

How do I check if an array contains duplicates?

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

How do you find duplicate numbers in an array if it contains multiple duplicates?

Simple Approach: The idea is to use nested loop and for each element check if the element is present in the array more than once or not. If present, then store it in a Hash-map.


1 Answers

If you sort the array, the duplicates are next to each other so that they are easy to find:

arr.sort();
var last = arr[0];
for (var i=1; i<arr.length; i++) {
   if (arr[i] == last) alert('Duplicate : '+last);
   last = arr[i];
}
like image 55
Guffa Avatar answered Nov 09 '22 12:11

Guffa