-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
  • 155,085
  • 27
  • 166
  • 222
James
  • 139
  • 9
  • 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. – Rohìt Jíndal 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
  • 12,566
  • 16
  • 32
  • 51
hgb123
  • 11,887
  • 3
  • 15
  • 33
  • 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
1

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
  • 13,536
  • 3
  • 21
  • 44
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)]);
Rohìt Jíndal
  • 16,572
  • 12
  • 64
  • 110