JS Built-ins
← Array65 / 226
ArrayArray.prototype.filterintermediate

Array.prototype.filter() β€” keep unique values

πŸ“– Usage Example
const nums = [1, 2, 2, 3, 3, 4]
nums.filter((v, i, a) => a.indexOf(v) === i)
// β†’ [1, 2, 3, 4]  (first occurrences only)

Use filter() with indexOf() to deduplicate an array by keeping only the first occurrence of each value.

Array.prototype.filter() β€” deduplication

By using filter with indexOf, you can keep only the elements whose first occurrence equals the current index, effectively removing duplicates.

Challenge: Implement filterUnique(arr) that returns items appearing exactly once (i.e. not duplicated).

filterUnique([1, 2, 2, 3, 3, 4]) // β†’ [1, 4]
filterUnique([1, 2, 3])          // β†’ [1, 2, 3]
πŸ’‘ Hints (2)
  • β€’ An element is unique if `arr.indexOf(val) === arr.lastIndexOf(val)`.
  • β€’ This checks that the first and last occurrence are the same index.