1

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

1
  • 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. Commented Oct 22, 2019 at 6:42

2 Answers 2

1

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);

Sign up to request clarification or add additional context in comments.

1 Comment

you mutate the original data.
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.