In JavaScript, How to Check If an Array Has Duplicate Values

In Javascript, how do I check if an array has duplicate values?

If you have an ES2015 environment (as of this writing: io.js, IE11, Chrome, Firefox, WebKit nightly), then the following will work, and will be fast (viz. O(n)):

function hasDuplicates(array) {
return (new Set(array)).size !== array.length;
}

If you only need string values in the array, the following will work:

function hasDuplicates(array) {
var valuesSoFar = Object.create(null);
for (var i = 0; i < array.length; ++i) {
var value = array[i];
if (value in valuesSoFar) {
return true;
}
valuesSoFar[value] = true;
}
return false;
}

We use a "hash table" valuesSoFar whose keys are the values we've seen in the array so far. We do a lookup using in to see if that value has been spotted already; if so, we bail out of the loop and return true.


If you need a function that works for more than just string values, the following will work, but isn't as performant; it's O(n2) instead of O(n).

function hasDuplicates(array) {
var valuesSoFar = [];
for (var i = 0; i < array.length; ++i) {
var value = array[i];
if (valuesSoFar.indexOf(value) !== -1) {
return true;
}
valuesSoFar.push(value);
}
return false;
}

The difference is simply that we use an array instead of a hash table for valuesSoFar, since JavaScript "hash tables" (i.e. objects) only have string keys. This means we lose the O(1) lookup time of in, instead getting an O(n) lookup time of indexOf.

Checking for duplicate strings in JavaScript array

The findDuplicates function (below) compares index of all items in array with index of first occurrence of same item. If indexes are not same returns it as duplicate.

let strArray = [ "q", "w", "w", "w", "e", "i", "u", "r"];
let findDuplicates = arr => arr.filter((item, index) => arr.indexOf(item) != index)

console.log(findDuplicates(strArray)) // All duplicates
console.log([...new Set(findDuplicates(strArray))]) // Unique duplicates

Check if an array contains duplicate values

You got the return values the wrong way round:

  • As soon as you find two values that are equal, you can conclude that the array is not unique and return false.

  • At the very end, after you've checked all the pairs, you can return true.

If you do this a lot, and the arrays are large, you might want to investigate the possibility of sorting the array and then only comparing adjacent elements. This will have better asymptotic complexity than your current method.

In JavaScript, how do I check if an array has duplicate multiple values?

You can create a separate function for this to check if element exists in list or not.

Try this:

function doesExistInList(list, obj) {  for (let i = 0; i < list.length; i++) {    if (list[i].x === obj.x && list[i].y === obj.y && list[i].z === obj.z) {      return true;    }  }  return false;}
let link = [];let obj = { "x": "1", "y": "2", "z": "3" };if (doesExistInList(link, obj) == false) { link.push(obj);//insert same object to list} else { alert("Duplicate");}console.log(link);

How can I check if the array of objects have duplicate property values?

Use array.prototype.map and array.prototype.some:

var values = [
{ name: 'someName1' },
{ name: 'someName2' },
{ name: 'someName4' },
{ name: 'someName2' }
];

var valueArr = values.map(function(item){ return item.name });
var isDuplicate = valueArr.some(function(item, idx){
return valueArr.indexOf(item) != idx
});
console.log(isDuplicate);

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

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

How to see if an array has 2 or more elements that are the same?

A simple way is to use a Set.

function doesContainDups(array) {
let set = new Set(array);
return set.size !== array.length;
}

console.log(doesContainDups(["item1", "item2", "item3"]));
console.log(doesContainDups(["item1", "item2", "item1"]));

How to count duplicate value in an array in javascript

function count() {    array_elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
array_elements.sort();
var current = null; var cnt = 0; for (var i = 0; i < array_elements.length; i++) { if (array_elements[i] != current) { if (cnt > 0) { document.write(current + ' comes --> ' + cnt + ' times<br>'); } current = array_elements[i]; cnt = 1; } else { cnt++; } } if (cnt > 0) { document.write(current + ' comes --> ' + cnt + ' times'); }
}
count();

How to find duplicate values in a JavaScript array of objects, and output only unique values?

You could use a Set in combination with Array#map and a spread operator ... in a single line.

Map returns an array with all names, which are going into the set initializer and then all values of the set are returned in an array.

var family = [{ name: "Mike", age: 10 }, { name: "Matt", age: 13 }, { name: "Nancy", age: 15 }, { name: "Adam", age: 22 }, { name: "Jenny", age: 85 }, { name: "Nancy", age: 2 }, { name: "Carl", age: 40 }],    unique = [...new Set(family.map(a => a.name))];
console.log(unique);

How can I check if an array has two or more of the same unknown strings in it?

There are a few ways you can do this:

1: Use the method Stevens Qiu suggested. If the length of the array and Set aren't equal, there was a repeat in the array. This is my favorite.

2: Iterate through the array. On each iteration, add that value to a hash. If the value is already in the hash, there was a repeat so return true.

3: Iterate through the array. On each iteration get the index of (indexOf()) the item and the last index (lastIndex()) of the item. If those values aren't equal, return true.

const arr = ['hi', 'bye', 'hi'];const arr2 = ['hi', 'bye', 'what'];
// Set size < arr length, so returns falseconsole.log(arr.length === new Set(arr).size);// Set size == arr length, so returns trueconsole.log(arr2.length === new Set(arr2).size);


Related Topics



Leave a reply



Submit