How to get distinct values from an array of objects in JavaScript?

前端 未结 30 3120
执笔经年
执笔经年 2020-11-22 05:29

Assuming I have the following:

var array = 
    [
        {\"name\":\"Joe\", \"age\":17}, 
        {\"name\":\"Bob\", \"age\":17}, 
        {\"name\":\"Carl\         


        
30条回答
  •  没有蜡笔的小新
    2020-11-22 05:55

    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());
    }
    

提交回复
热议问题