Array of objects and i want to return true if any key value pair in the object is duplicate

Viewed 79

I am fairly new to JS, I am struggling with a problem where there is an array of objects and i want to return true if any key value pair in the object is duplicate

var lookupValues = [{"key":"xiomi","value":"phone","id":1},{"key":"samsung","value":"tab",id:2},{"key":"blackberry","value":"phone","id":3},{"key":"xiomi","value":"tab","id":4},{"key":"asus","value":"phone",id:5}]}

Since key: "Xiomi" came twice so function should return true

i tried using lodash functions

var uniqueLookup =_uniqBy(lookupValues,'key')
if(_.isEqual(uniqueLookup, lookup)) return true

works but i guess i am missing something

3 Answers

You are on the right track. Compare the length of the array to the array shortened by checking if the key is unique.

var lookupValues = [{"key":"xiomi","value":"phone","id":1},{"key":"samsung","value":"tab",id:2},{"key":"blackberry","value":"phone","id":3},{"key":"xiomi","value":"tab","id":4},{"key":"asus","value":"phone",id:5}];
console.log(_.uniqBy(lookupValues,"key").length !== lookupValues.length);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.19/lodash.min.js"></script>

Here how you can do this in VanillaJs.

Set is a new data structure that JavaScript got in ES6. It’s a collection of unique values. We put into that the list of property values we get from using map(), which how we used it will return this array:

[xiomi,Samsung,blackberry,xiomi,asus]

Passing through Set, we’ll remove the duplicates i.e xiomi and at last ... is the spread operator, which will expand the Set values into an array.

Now if length of this new array is equal to your lookupValues.length then it has no duplicates else duplicates are present.

var lookupValues = [{"key":"xiomi","value":"phone","id":1},{"key":"samsung","value":"tab",id:2},{"key":"blackberry","value":"phone","id":3},{"key":"xiomi","value":"tab","id":4},{"key":"asus","value":"phone",id:5}]

const isDuplicate = (lookupValues) => !([...new Set(lookupValues.map(obj => obj.key))].length === lookupValues.length)

console.log(isDuplicate(lookupValues))

I made a vanilla Javascript code snippet with es6 Set object.

var lookupValues = [{"key":"xiomi","value":"phone","id":1},{"key":"samsung","value":"tab",id:2},{"key":"blackberry","value":"phone","id":3},{"key":"xiomi","value":"tab","id":4},{"key":"asus","value":"phone",id:5}]
const keys = lookupValues.map((v) => v.key)
const keySetSize = new Set(keys).size
const hasDuplicate = keys.length > keySetSize
console.log(hasDuplicate)
Related