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
-
Also how you merge 2 arrays and respect the indexes at the same time. If on one array you have arr1[0] = 'Test' and arr2[0] = 'Test2' how you respect the index????? You can merge and respect, the only solution for that is yo create and object and again it is now the right way.George Stavrou– George Stavrou2019年10月22日 06:42:01 +00:00Commented Oct 22, 2019 at 6:42
2 Answers 2
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);
answered Oct 22, 2019 at 6:42
Mamun
69k9 gold badges51 silver badges62 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Nina Scholz
you mutate the original data.
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);
answered Oct 22, 2019 at 6:43
cнŝdk
32.2k7 gold badges62 silver badges81 bronze badges
Comments
lang-js