Files
30-seconds-of-code/snippets/uniqueElementsByRight.md
30secondsofcode 2fc7529f5b Travis build: 110
2018-07-18 18:03:57 +00:00

789 B

uniqueElementsByRight

Returns all unique values of an array, based on a provided comparator function.

Use Array.reduce() and Array.some() for an array containing only the last unique occurence of each value, based on the comparator function, fn. The comparator function takes two arguments: the values of the two elements being compared.

const uniqueElementsByRight = (arr, fn) =>
  arr.reduceRight((acc, v) => {
    if (!acc.some(x => fn(v, x))) acc.push(v);
    return acc;
  }, []);
uniqueElementsByRight(
  [
    { id: 0, value: 'a' },
    { id: 1, value: 'b' },
    { id: 2, value: 'c' },
    { id: 1, value: 'd' },
    { id: 0, value: 'e' }
  ],
  (a, b) => a.id == b.id
); // [ { id: 0, value: 'e' }, { id: 1, value: 'd' }, { id: 2, value: 'c' } ]