Files
30-seconds-of-code/snippets/js/s/function-based-reversed-array-unique-values.md
Angelos Chalaris 9d032ce05e Rename js snippets
2023-05-19 20:23:47 +03:00

1000 B

title, type, language, tags, cover, dateModified
title type language tags cover dateModified
Reversed unique values in array based on function snippet javascript
array
beach-from-above 2021-10-13T19:29:39+02:00

Finds all unique values of an array, based on a provided comparator function, starting from the right.

  • Use Array.prototype.reduceRight() and Array.prototype.some() to create an array containing only the last unique occurrence 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' } ]