cessother
cessother

Reputation: 127

Merging an array of arrays with a simple array

I'd like to merge two arrays in one but the indexes have to be respected as data are dynamics

I've tried this :

labels[0].forEach(element=>{
  labels[0]=(element.map((e, i) => e +','+ tableauCompare[i]));
})

but I get two strings

My Input:

[
    ["string1", "string2","string3"],
    ["string1b", "string2b","string3b"]
]

["string4", "string4b"]

Expected output:

[
    ["string1", "string2","string3","string4"],
    ["string1b", "string2b","string3b", "string4b"]
]

I expect a new array, like the last one, but I get an array with two strings

Upvotes: 1

Views: 60

Answers (2)

Mamun
Mamun

Reputation: 68933

Instead of map() you can use Array.prototype.push() and Array.prototype.concat() like the following way:

var labels = [
    ["string1", "string2","string3"],
    ["string1b", "string2b","string3b"]
]
var tableauCompare = ["string4", "string4b"];
var res = [];
labels.forEach((element, i)=>{
  res.push(element.concat(tableauCompare[i]));
});
console.log(res);

Upvotes: 1

cнŝdk
cнŝdk

Reputation: 32145

You can just use a .map() method call on the first array and concat each element with the respective element from compareTableau array by index.

var labels = [
  ["string1", "string2", "string3"],
  ["string1b", "string2b", "string3b"]
];
var tableauCompare = ["string4", "string4b"];

var result = labels.map((el, i) => el.concat(tableauCompare[i]));

Demo:

var labels = [
  ["string1", "string2", "string3"],
  ["string1b", "string2b", "string3b"]
];
var tableauCompare = ["string4", "string4b"];

var result = labels.map((el, i) => el.concat(tableauCompare[i]));

console.log(result);

Upvotes: 1

Related Questions