-1

I have below javascript array of object problem in which i have tag array property inside array of object. Tag array contain some value in each array of object. I wanted to get unique tag value from each array of object and combine into single array which will contain only unique tag.

const obj = [{
  name: "ABC",
  tag: ["abc", "xyz"]
}, {
  name: "USA",
  tag: ["abc", "suv"]
}, {
  name: "ABC",
  tag: ["pot", "xyz"]
}]

I need the unique tag item into single array as per below.

const unique = ["abc", "xyz", "suv", "pot"];
mplungjan
  • 169,008
  • 28
  • 173
  • 236
James
  • 371
  • 3
  • 12
  • Does this answer your question? [Get all unique values in a JavaScript array (remove duplicates)](https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates) – Nguyễn Văn Phong Feb 25 '22 at 06:53
  • @James I added an answer. Did you get a chance to look into that. Hope it will work as per your expectation. – Debug Diva Mar 01 '22 at 14:03

3 Answers3

3

You could use flatMap and Set

const obj = [
  { name: 'ABC', tag: ['abc', 'xyz'] },
  { name: 'USA', tag: ['abc', 'suv'] },
  { name: 'ABC', tag: ['pot', 'xyz'] },
]

const res = [...new Set(obj.flatMap(({tag}) => tag))];

console.log(res)
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
hgb123
  • 13,869
  • 3
  • 20
  • 38
  • 1
    Hi hgb123, As @mplungjan said, you should use `Destructure` to make your code more concise. You can see [here](https://stackoverflow.com/a/67265714/9071943). I've just updated your answer accordingly. – Nguyễn Văn Phong Feb 25 '22 at 06:45
2

A set will give you unique values:

const obj = [{
  name: "ABC",
  tag: ["abc", "xyz"]
}, {
  name: "USA",
  tag: ["abc", "suv"]
}, {
  name: "ABC",
  tag: ["pot", "xyz"]
}]

const unique = [...new Set(obj.flatMap(({tag}) => tag))];

console.log(unique)
jsejcksn
  • 27,667
  • 4
  • 38
  • 62
0

You can use Set to filtered out the unique elements from an array.

Demo :

const obj = [{
  name: "ABC",
  tag: ["abc", "xyz"]
}, {
  name: "USA",
  tag: ["abc", "suv"]
}, {
  name: "ABC",
  tag: ["pot", "xyz"]
}];

let arr = [];

obj.forEach((item) => {
    arr.push(...item.tag)
})

console.log([...new Set(arr)]);
Debug Diva
  • 26,058
  • 13
  • 70
  • 123