Menu

gitpiper

uniqueElementsBy javascript Code Snippet in 2023

arrayintermediate

Last Updated: 28 January 2023

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

  • Use Array.prototype.reduce() and Array.prototype.some() to create an array containing only the first 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 uniqueElementsBy = (arr, fn) => arr.reduce((acc, v) => { if (!acc.some(x => fn(v, x))) acc.push(v); return acc; }, []);
uniqueElementsBy( [ { 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: 'a' }, { id: 1, value: 'b' }, { id: 2, value: 'c' } ]

javascript snippet similar to uniqueElementsBy For You in January 2023

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2023 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️