0

I was working on some code that return the unique objects in an array.

I found some code that does the trick, but it's not exactly what I need.

Right now let's say I have this array:

restuls= [
        {
            name: "name 1",
            description: "",
            group: "group 1"
        },
        {
             name: "name 1",
            description: "",
            group: "group 1"
        },
        {
            name: "name 1",
            description: "",
            group: "group 2"
        },
]

With the code below, I find all unique objects in this array, meaning, if ANY of the values in the object are different, it will be a unique. So, in this case It will return 2 objects (because on the 3rd object --> group: "group 2").

   var array = results,
      unique = Array.from(
        new Set(array.map(o => JSON.stringify(o))),
        s => JSON.parse(s)
       );

What I actually want is that it removes all duplicate objects, but only looking at "name" So, in this case, all 3 objects have the same name, so only one should be displayed.

Any ideas?

3

2 Answers 2

1

You can do this using for and a Set -

const input =
  [{name: "name 1",description: "",group: "group 1"},{name: "name 1",description: "",group: "group 1"},{name: "name 1",description: "",group: "group 2"},]

const result =
  []
  
const seen =
  new Set
  
  
for (const v of input)
  if (seen.has(v.name))
    continue
  else
    (result.push(v), seen.add(v.name))
    
console.log(result)

Output -

[
  {
    "name": "name 1",
    "description": "",
    "group": "group 1"
  }
]

Or using a Map -

const input =
  [{name: "name 1",description: "",group: "group 1"},{name: "name 1",description: "",group: "group 1"},{name: "name 1",description: "",group: "group 2"},]
 
const seen =
  new Map
    
for (const v of input)
  if (seen.has(v.name))
    continue
  else
    seen.set(v.name, v)

const result =
  Array.from(seen.values())
  
console.log(result)

Output -

[
  {
    "name": "name 1",
    "description": "",
    "group": "group 1"
  }
]
Sign up to request clarification or add additional context in comments.

Comments

0

results= [
        {
            name: "name 1",
            description: "",
            group: "group 1"
        },
        {
             name: "name 1",
            description: "",
            group: "group 1"
        },
        {
            name: "name 1",
            description: "",
            group: "group 2"
        },
]

const map = new Map();

results.forEach(x => {
  if(!map.has(x.name))
  { map.set(x.name, x) }
});

const arr = Array.from(map).map(x => x[1]);
console.log(arr)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.