简体   繁体   中英

How to combine elements in 2D array

I have a 2D array that looks like this:

var colors = [["red", "blue"], ["green", "black"], ["orange", "purple"]];

How can I run a simple method to combine the elements in each array, like this:

[["red blue"], ["green black"], ["orange purple"]]

You could achieve this via map and join :

 const colors = [["red", "blue"], ["green", "black"], ["orange", "purple"]]; const merged = colors.map(x => [x.join(' ')]); console.log(merged);

It seems odd that you'd want the merged items to each be an array containing a single item but that's what you asked for. If you wanted an array of strings instead, you'd just remove the square brackets from around the join call:

 const merged = colors.map(x => x.join(' '));

 // ["red blue", "green black", "orange purple"]
const merged = colors.map(([first, second]) => `${first} ${second}`)

Also you can deconstruct these params and join them using templates.

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