Checking for Duplicate Strings in JavaScript Array

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

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

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.

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

Javascript: Duplicate each string value in an array

You probably want to use .repeat() function like:

const duplicate = (v) => v.split("").map(i => i.repeat(2));
console.log(duplicate("3ff"));

How to i determine if in the same array there are duplicate values?

You could iterate the array by step of two and get key and value for looking for the same group.

If not found add a new group to the result set.

At last add the value to the group.

var data = [11, 2, 11, 3, 11, 4, 9, 5],    result = [];
for (let i = 0; i < data.length; i += 2) { let key = data[i], value = data[i + 1], group = result.find(([q]) => q === key);
if (!group) result.push(group = [key, 0]); group[1] += value;}
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Checking for duplicate property values in an array of nested objects

There were quite a few errors in your code, I have fixed them. What seemed to confuse you the most was that you had an array of a single item, that is an object, which has an items member that's an array as well. So, we needed to refer data[0].items[x] instead of data[x]. Also, in your checkIfPresent function you checked whether data contains the item, which is obviously true. Always. Instead, you wanted to check whether an item of the same name was already processed, so you needed to check whether arr already had this value. Finally, arr is initialized in every iteration of your loop, which removes anything that was stored in an earlier iteration and makes it unaccessible outside the loop. I moved the initialization outside the loop. Also, since your data has an array, it seems that you may have several shoppings. In which case you can wrap another loop around the loop that you already have and loop data's main index as well.

let data = [
{
"email": "tshepo@email.com",
"status": "OPEN",
"items": [
{
"name": "hamster",
"quantity": 2,
"price": 20
},
{
"name": "saw dust",
"quantity": 1,
"price": 20
},
{
"name": "hamster-cage",
"quantity": 1,
"price": 150
},
{
"name": "book: how to care for your hamster",
"quantity": 1,
"price": 150
},
{
"name": "hamster-cage",
"quantity": 1,
"price": 150
}
]
}
]
function checkIfPresent(key, array){
let ans = array.findIndex((obj) => obj.name === key)
return ans;
}

let arr = [];var ans;
for(let x = 0; x < data[0].items.length; x++)
{
if((ans = checkIfPresent(data[0].items[x].name, arr)) >= 0){
arr[ans].quantity += data[0].items[x].quantity;
}else{
arr.push(data[0].items[x]);
}
}
console.log(arr);


Related Topics



Leave a reply



Submit