-2

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

letters
  • 37
  • 6
  • 1
    Does this answer your question? [Checking for duplicate strings in JavaScript array](https://stackoverflow.com/questions/49215358/checking-for-duplicate-strings-in-javascript-array) – PM 77-1 Oct 03 '22 at 21:15
  • @PM77-1 but my array contains objects – letters Oct 03 '22 at 21:16
  • @letters I recommend showing a basic example of your array, that will give users the ability to test out and get a working example based on your actual data. – imvain2 Oct 03 '22 at 21:24
  • some() is what you are looking for `const hasDupe = arr.some(({name}) => name === value )` – epascarello Oct 03 '22 at 21:27
  • How do you define the "duplicate" for your objects? – PM 77-1 Oct 03 '22 at 21:35
  • 1
    @epascarello wouldn't that return true also when only 1 element fulfils the condition? I think OP needs at least 2 – GrafiCode Oct 03 '22 at 21:39
  • @GrafiCode yes at least 2 – letters Oct 03 '22 at 21:59
  • You'll need to explain "at least 2". It changes the whole task you're doing from "checking if value exists in arr" to "checking arr for duplicates in general". And you didn't provide enough supporting code for us to be able to tell. – James Oct 03 '22 at 22:04
  • Um, not sure where "2" came from when it would be one.... makes no sense. – epascarello Oct 04 '22 at 00:36

2 Answers2

1

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) )
 
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
0

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.

Jose Marin
  • 802
  • 1
  • 4
  • 15