Files
30-seconds-of-code/snippets/filterUniqueBy.md
Isabelle Viktoria Maciohsek 27c168ce55 Bake date into snippets
2021-06-13 13:55:00 +03:00

873 B

title, tags, firstSeen, lastUpdated
title tags firstSeen lastUpdated
filterUniqueBy array,intermediate 2020-11-02T19:41:07+02:00 2020-11-02T19:41:07+02:00

Creates an array with the unique values filtered out, based on a provided comparator function.

  • Use Array.prototype.filter() and Array.prototype.every() to create an array containing only the non-unique values, based on the comparator function, fn.
  • The comparator function takes four arguments: the values of the two elements being compared and their indexes.
const filterUniqueBy = (arr, fn) =>
  arr.filter((v, i) => arr.some((x, j) => (i !== j) === fn(v, x, i, j)));
filterUniqueBy(
  [
    { id: 0, value: 'a' },
    { id: 1, value: 'b' },
    { id: 2, value: 'c' },
    { id: 3, value: 'd' },
    { id: 0, value: 'e' }
  ],
  (a, b) => a.id == b.id
); // [ { id: 0, value: 'a' }, { id: 0, value: 'e' } ]