0

Is this possible to use a feature similar to this below that will return both properties without having to create a second array. The second property Name will always be the same.

const data = [{
    Group: 'A',
    Name: 'SEAN'
}, {
    Group: 'B',
    Name: 'PAUL'
}, {
    Group: 'A',
    Name: 'SEAN'
}, {
    Group: 'B',
    Name: 'PAUL'
}];

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

return ["A", "B"]

https://codepen.io/vlad-bezden/pen/OMEXJz

I am trying to return

  [{
   Group: 'A',
   Name: 'SEAN'
   }, 
 {
   Group: 'B',
   Name: 'PAUL'
 }]
user10609979
  • 389
  • 2
  • 3
  • 11
  • 3
    How does the code above not accomplish what you are trying to do? – Luca Kiebel Feb 19 '19 at 11:46
  • Do you want to return `['A','B']` or something else? – Maheer Ali Feb 19 '19 at 11:48
  • Try this [remove duplicates from array of objects](https://stackoverflow.com/questions/2218999/remove-duplicates-from-an-array-of-objects-in-javascript) – dporechny Feb 19 '19 at 11:50
  • 1
    Possible duplicate of [Remove duplicates from an array of objects in JavaScript](https://stackoverflow.com/questions/2218999/remove-duplicates-from-an-array-of-objects-in-javascript) – adiga Feb 19 '19 at 11:54

2 Answers2

1

You can use a forEach

Here the idea is included is used to keep track of the groups added into op. Then we check if the group is already in the included object, if it is we do nothing, otherwise we add it to op.

const data = [{Group: 'A', Name: 'SEAN'}, { Group: 'B', Name: 'PAUL'}, { Group: 'A',Name: 'SEAN'}, {Group: 'B',Name: 'PAUL'}];

let op = []
let included = {}

data.forEach((e)=>{
  if( !included[e.Group] ){
    op.push(e)
    included[e.Group] = true
  }
})

console.log(op)
Oliver Nybo
  • 560
  • 1
  • 6
  • 24
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
0

If you are trying to remove duplicate objects from an array and get an array of unique objects you can use .reduce. Here I use .reduce to create an object of keys. The keys are a combination of both the Group and Name, which allows you to check if your reduced object has the value within it already.

Lastly, I use Object.keys to get the unique objects stored as the values at each combination.

See example below:

'use strict'

const data = [{
    Group: 'A',
    Name: 'SEAN'
}, {
    Group: 'B',
    Name: 'PAUL'
}, {
    Group: 'A',
    Name: 'SEAN'
}, {
    Group: 'B',
    Name: 'PAUL'
}];

let unique = Object.values(data.reduce((acc, {Group, Name}) => {
  const key = `${Group}:${Name}`;
  !(key in acc) && (acc[key] = {Group, Name});
  return acc;
}, {}));

console.log(unique);

This will give you a unique array of objects by checking both the Group and the Name

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • when i try to use this code i get an error saying "Expected an assignment or function call and instead saw an expression no-unused-expressions". on the line key in acc ? acc : acc[key] = {Group, Name}; – user10609979 Feb 19 '19 at 12:15