JS Built-ins
← Array176 / 226
ArrayArray.prototype.someintermediate

Array.prototype.some() β€” detect duplicates

πŸ“– Usage Example
const arr = [1, 2, 3, 4, 5]
arr.some(n => { console.log(n); return n === 3 })
// logs 1, 2, 3 β€” stops early

some() short-circuits as soon as a truthy result is found, saving unnecessary iterations.

Array.prototype.some() β€” early exit with indexOf

some() is ideal for detecting duplicates: check whether any element appears at a different index than its first occurrence using indexOf.

Challenge: Implement containsDuplicate(arr) that returns true if any element appears more than once.

containsDuplicate([1, 2, 3, 2]) // β†’ true
containsDuplicate([1, 2, 3])    // β†’ false
πŸ’‘ Hints (2)
  • β€’ `indexOf` always returns the **first** occurrence index. If `idx` differs from `indexOf(val)`, the element is a duplicate.
  • β€’ This is O(nΒ²) β€” for large arrays, a `Set` approach is more performant.