skip to Main Content
const data = [{
    id: 1,
    Group: 'A',
    Name: 'SD'
}, {
    id: 2,
    Group: 'B',
    Name: 'FI'
}, {
    id: 3,
    Group: 'A',
    Name: 'SD'
}, {
    id: 4,
    Group: 'B',
    Name: 'CO'
}];

let unique = [...new Set(data.map(item => item.Group))];
console.log(unique);

Expecting only return district array object in the data 0 index value should not return again as it does already have same group and name value.

https://jsfiddle.net/k3p7xfcw/

Thank You

2

Answers


  1. You can try Unique by multiple properties ( Group and Name )

    let result = data.filter((v,i,a)=>a.findIndex(v2=>['Group','Name'].every(k=>v2[k]
    ===v[k]))===i)
    

    https://jsfiddle.net/G2jakhmola/qutranps/1/

    Login or Signup to reply.
  2. using JS array filter

    const data = [{
        Group: 'A',
        Name: 'SD'
    }, {
        Group: 'B',
        Name: 'FI'
    }, {
        Group: 'A',
        Name: 'SD'
    }, {
        Group: 'B',
        Name: 'CO'
    }];
    
    const uniqueGroups = data.filter((item, index, array) => {
      // Return true only if the current item is the first occurrence of the group in the array
      return array.findIndex((t) => t.Group === item.Group) === index;
    });
    
    console.log(uniqueGroups); // [{Group: 'A', Name: 'SD'}, {Group: 'B', Name: 'FI'}]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search