30 seconds of code

  Back to Home



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

Use Array.prototype.reduceRight() and Array.prototype.some() for 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;
  }, []);