How to Find and Return a Duplicate Value in Array

How to find and return a duplicate value in array

a = ["A", "B", "C", "B", "A"]
a.detect{ |e| a.count(e) > 1 }

I know this isn't very elegant answer, but I love it. It's beautiful one liner code. And works perfectly fine unless you need to process huge data set.

Looking for faster solution? Here you go!

def find_one_using_hash_map(array)
map = {}
dup = nil
array.each do |v|
map[v] = (map[v] || 0 ) + 1

if map[v] > 1
dup = v
break
end
end

return dup
end

It's linear, O(n), but now needs to manage multiple lines-of-code, needs test cases, etc.

If you need an even faster solution, maybe try C instead.

And here is the gist comparing different solutions: https://gist.github.com/naveed-ahmad/8f0b926ffccf5fbd206a1cc58ce9743e

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

Check for duplicate entries in array but ONLY return values that are duplicated

Depending on what you want displayed (for example this just gives the ID of a row) it would be better to try it in SQL...

SELECT ID 
FROM `barcodes`
GROUP BY ID
HAVING count(ID)>1

The idea is to just retrieve ID's where the count value is more than one.

So this could look like...

$query = mysqli_query($dbc, "SELECT barcode 
FROM `barcodes`
GROUP BY barcode
HAVING count(barcode)>1");

$result_array = mysqli_fetch_all($query, MYSQLI_ASSOC);

print_r($result_array);

If you wanted to have the number of times it exists, just add the count to the SELECT list...

SELECT ID, count(ID) times
FROM `barcodes`
GROUP BY ID
HAVING count(ID)>1

Get list of duplicate objects in an array of objects

You can use Array#reduce to make a counter lookup table based on the id key, then use Array#filter to remove any items that appeared only once in the lookup table. Time complexity is O(n).

const values = [{id: 10, name: 'someName1'}, {id: 10, name: 'someName2'}, {id: 11, name:'someName3'}, {id: 12, name: 'someName4'}];
const lookup = values.reduce((a, e) => { a[e.id] = ++a[e.id] || 0; return a;}, {});
console.log(values.filter(e => lookup[e.id]));

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

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

Javascript: How to find first duplicate value and return its index?

Change your code with the following

    var numbers4 = [5, 2, 3, 4, 2, 6, 7, 1, 2, 3];
var firstIndex = "";
var isMatch=false;
for (var a = 0; a < numbers4.length; a++) {
for (var b = a+1; b < numbers4.length; b++) {
if (numbers4[a] === numbers4[b]){
firstIndex = numbers4.indexOf(numbers4[a]);
isMatch=true;
break;
}
}
if (isMatch) {break;}
}
console.log(firstIndex);

Find duplicate objects in array and return new array of object with number of duplicates as a new property

I think you'd be best suited by creating a helper object. A helper object will initially be empty, but will become populated slowly by what you're reading through. I'm going to assume that the keys in your array are consistent.

const keys = ["Name","Type"]
var counterObj = {}
let keyForCounterObj
arrayOfObjects.forEach((obj)=>{
keyForCounterObj = ''
keys.forEach((key)=>{
keyForCounterObj += String(obj[key])
}
if(counterObj[keyForCounterObj]){
counterObj[keyForCounterObj].times ++
}else{
counterObj[keyForCounterObj] = {
...obj,
times:1
}}}

Let's break that down, because I understand that it might be a little bit confusing if you've never seen this setup before.

We're looping through each object in the array, and we're constructing a key based on all of the values that this object is storing. For example, arrayOfObjects[0] will create a key of "AppleFruit." (I'm using the String() method just in case this is being applied to an object with only integer or floating point values, as those are invalid to create a key in javaScript. It isn't necessary for your specific question)

Once we have that key, we check to see if it exists in our counterObject. If it does not exist, then we define it. We set the "times" attribute to 1, because we just created this object; it wouldn't exist unless we had just found it.

If the object does already exist, then we just increment the "times" attribute. At the end, we have an object that looks like this:

counterObj = {
AppleFruit: {
Name:"Apple",
Type:"Fruit",
times:3,
},
CarrotVegetable:{
Name:"Carrot",
Type:"Vegetable",
times:4,
}
}

Okay, so now we have an object of objects. Let's turn that into an array!

let newArrayOfObjects = []
const counterObjKeys = Object.keys(counterObj)
counterObjKeys.forEach((key)=>{
newArrayOfObjects.push(counterObj[key])
}

This will return the final value in the format that you specified!



Related Topics



Leave a reply



Submit