简体   繁体   中英

How to combine all unique element in any given array property from array of object into single array in javascript?

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"];

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)

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)

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)]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM