Reputation: 85
I have an below array and wanted to return just true
or false
if we have two property with same value in array of object. As you can see id with 123
have same value as "one". If both are match then return true
.
const data = [
{id: 123, value: "One"},
{id: 123, value: "One"},
{id: 143, value: "Two"},
{id: 153, value: "Three"}
]
Upvotes: 0
Views: 508
Reputation: 5205
One approach could be this:
const data = [{id: 123, value: "One"},{id: 123, value: "One"},{id: 143, value: "Two"}, {id: 153, value: "Three"}]
for(let i=0; i< data.length; i++){
for(let j=i+1; j<data.length; j++){
if(JSON.stringify(data[i]) === JSON.stringify(data[j])){
console.log(true);
break;
}
}
}
A better approach with O(N) complexity would be this:
const data = [{id: 123, value: "One"},{id: 123, value: "One"},{id: 143, value: "Two"}, {id: 153, value: "Three"}]
var stringifyElements = data.map(i=> JSON.stringify(i));
console.log(stringifyElements)
var hashMap = {};
for(var i =0; i<stringifyElements.length; i++){
if(hashMap[stringifyElements[i]] === 1){
console.log(true);
break;
}else{
hashMap[stringifyElements[i]] = 1
}
}
Upvotes: 1
Reputation: 15530
You may check whether the size of unique Set
of hashes (keys and values concatenated) of all objects within array is less than source array length (which may happen only if there're non-unique key/value combinations):
const dup = [{id: 123, value: "One"},{id: 123, value: "One"},{id: 143, value: "Two"}, {id: 153, value: "Three"}],
noDup = [{id: 1234, value: "One"},{id: 123, value: "One"},{id: 143, value: "Two"}, {id: 153, value: "Three"}],
hasDup = arr =>
new Set(arr.map(({id,value}) => `id|${id}|value|${value}`)).size < arr.length
console.log(hasDup(dup)) //true
console.log(hasDup(noDup)) //false
Or, if you need to check for duplicates across all key/value combinations:
const hasDup = arr =>
new Set(arr.map(o => Object.entries(o).flat().join('|'))).size < arr.length
Upvotes: 2
Reputation: 10025
Let me know if it needs an explanation.
function doJob(data){
for(let i = 0; i < data.length; i++){
let count = data.filter(item => (item.id === data[i].id && item.value === data[i].value)).length;
if(count > 1) return true
}
return false;
}
const data = [
{id: 123, value: "One"},
{id: 123, value: "One"},
{id: 143, value: "Two"},
{id: 153, value: "Three"}
]
console.log(doJob(data))
Upvotes: 0