Assuming I have the following:
var array =
[
{\"name\":\"Joe\", \"age\":17},
{\"name\":\"Bob\", \"age\":17},
{\"name\":\"Carl\
Here's a versatile solution that uses reduce, allows for mapping, and maintains insertion order.
items: An array
mapper: A unary function that maps the item to the criteria, or empty to map the item itself.
function distinct(items, mapper) {
if (!mapper) mapper = (item)=>item;
return items.map(mapper).reduce((acc, item) => {
if (acc.indexOf(item) === -1) acc.push(item);
return acc;
}, []);
}
Usage
const distinctLastNames = distinct(items, (item)=>item.lastName);
const distinctItems = distinct(items);
You can add this to your Array prototype and leave out the items parameter if that's your style...
const distinctLastNames = items.distinct( (item)=>item.lastName) ) ;
const distinctItems = items.distinct() ;
You can also use a Set instead of an Array to speed up the matching.
function distinct(items, mapper) {
if (!mapper) mapper = (item)=>item;
return items.map(mapper).reduce((acc, item) => {
acc.add(item);
return acc;
}, new Set());
}