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"]]
CodePudding user response:
const merged = colors.map(([first, second]) => `${first} ${second}`)
Also you can deconstruct these params and join them using templates.
CodePudding user response:
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"]