I am doing like this, this is my code to know if there are duplicates
const value = 'a'
const value2 = 'c'
const arr = [{
name: 'a'
}, {
name: 'b'
}]
const result = arr.filter((d) => d.name === value).length !== 1
console.log(result)
const result2 = arr.filter((d) => d.name === value2).length !== 1
console.log(result2)
there is another way to do this properly? with .some(), .includes or other functions, i think my function its hard
note: arr contains objects
CodePudding user response:
I think your logic could fail with the case I fix below:
const value = 'a'
const value2 = 'c'
const arr = [{
name: 'a'
}, {
name: 'b'
},
{
name: 'a'
}
]
const result = arr.some((d) => d.name === value)
console.log(result)
const result2 = arr.some((d) => d.name === value2)
console.log(result2)
Semantically and better in performance I think it is better to use some. It will stop iterating with the first success match found.
CodePudding user response:
you can use Array.reduce()
const
value = 'a'
, value2 = 'c'
, arr = [{ name: 'a' }, { name: 'b' }]
, uniqElm = x => (1 === arr.reduce((r,{name}) => r (name===x)?1:0,0))
;
console.log( value, ', is present and unique ?', uniqElm(value) )
console.log( value2, ', is present and unique ?', uniqElm(value2) )