简体   繁体   English

Javascript:将所有数组合并为一个

[英]Javascript : Merge All Array into one

I have an array of arrays which I want to marge into one and remove duplicate values.我有一个 arrays 数组,我想将其合并为一个并删除重复值。

 let arr = [ { label:'XYZ', colors:['black','white','blue'] }, { label:'PQR', colors:['orange','yellow','white'] }, { label:'ABC', colors:['black','pink','blue'] }, ] let updatedArr = [] for(let i=0 i< arr.length; i++ ){ updatedArr.push( arr[i].reduce((a, b) => [...a, ...b], []) ) }

I want all the colors array value into one array and remove duplicate values as well.我希望将所有 colors 数组值放入一个数组中,并删除重复值。

Any help would be great.任何帮助都会很棒。

To get a concatenated list of all values you can use flatMap() .要获取所有值的串联列表,您可以使用flatMap() And to deduplicate you can use [...new Set(duplicates)] , which creates a Set of unique elements and spreads it into an array.要进行重复数据删除,您可以使用[...new Set(duplicates)] ,它创建一唯一元素并将其传播到一个数组中。

 let arr = [{ label: 'XYZ', colors: ['black', 'white', 'blue'] }, { label: 'PQR', colors: ['orange', 'yellow', 'white'] }, { label: 'ABC', colors: ['black', 'pink', 'blue'] }, ] let colors = [...new Set(arr.flatMap(obj => obj.colors))] console.log(colors)

Use Array.prototype.flat for flatting the array, and then use a Set for distincting values and then create an array from the set using the Spread operator.使用Array.prototype.flat来展平数组,然后使用Set来区分值,然后使用Spread运算符从集合中创建一个数组。

 let arr = [{ label: 'XYZ', colors: ['black', 'white', 'blue'] }, { label: 'PQR', colors: ['orange', 'yellow', 'white'] }, { label: 'ABC', colors: ['black', 'pink', 'blue'] }, ] const vals = [...new Set(arr.map(i => i.colors).flat())] console.log(vals)

You can use reduce and forEach .您可以使用reduceforEach Inside reduce call back use forEach to iterate the colors array & if accumulator does not include the color then push that color to accumulator内部减少回调使用forEach迭代colors数组&如果accumulator不包含颜色,则将该颜色推送到累加器

 let arr = [{ label: 'XYZ', colors: ['black', 'white', 'blue'] }, { label: 'PQR', colors: ['orange', 'yellow', 'white'] }, { label: 'ABC', colors: ['black', 'pink', 'blue'] }, ] let mergedColor = arr.reduce((acc, curr) => { curr.colors.forEach((item) => { if (acc.indexOf(item) === -1) { acc.push(item) } }) return acc; }, []); console.log(mergedColor)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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