Search code examples
javascriptarraysecmascript-6ecmascript-2016

How to select multiple specific property with distinct value from javascript array


Suppose I have a Javascript array like below.

const data = [   
    { group: 'A', name: 'SD', testid:1},    
    { group: 'B', name: 'FI',testid:2  },    
    { group: 'A', name: 'MM', testid:1 },   
    { group: 'B', name: 'CO', testid:2 },   
    { group: 'A', name:  'QW',  testid:1 } 
];

I want to get two specific properties(group and testid).

I would like to retrieve unique values for those properties in my end result. So my end result will be

{group:A,testid:1},{group:B,testid:2}

What I have tried so far is below.

  data.map(item=>item.group).

But this will give me only one property and without any distinct values How can I achieve this using latest ecmascript syntax in Javascript


Solution

  • you can reduce the array and check every time if the pair exists:

    data.reduce((prev, el) =>{
        if(prev.some(o => o.group == el.group && o.testid == el.testid))
             return prev;
        return [...prev, {group:el.group, testid:el.testid}]
    }, [])
    

    const data = [   
        { group: 'A', name: 'SD', testid:1},    
        { group: 'B', name: 'FI',testid:2  },    
        { group: 'A', name: 'MM', testid:1 },   
        { group: 'B', name: 'CO', testid:2 },   
        { group: 'A', name:  'QW',  testid:1 } 
    ];
    let result = data.reduce((prev, el) =>{
        if(prev.some(o => o.group == el.group && o.testid == el.testid))
             return prev;
        return [...prev, {group:el.group, testid:el.testid}]
    }, []);
    
    console.log(result);