Reputation: 1586
I am having 4 arrays like below
array1 = ["one", "two", "three"];
array2 = ["1", "2", "3"];
array3 = ["a", "b", "c"];
array4 = ["10", "20", "30"];
By using the elements of these arrays I need to create another set of arrays like below
oneArray = ["one", "1", "a", "10"];
twoArray = ["two", "2", "b", "20"];
threeArray = ["three", "3", "c", "30"];
Is there any simple way of doing this?
Upvotes: 0
Views: 534
Reputation: 368
Try this code. it will solve your problem.
array1 = ["one", "two", "three", "four", "five", "six" ];
array2 = ["1", "2", "3", "4", "5", "6"];
array3 = ["a", "b", "c", "e", "f", "g"];
array4 = ["10", "20", "30", "40", "50", "60"]
array5 = ["1", "2", "3", "4", "5", "6"]
finalArray = [
array1,
array2,
array3,
array4,
array5
];
function joinNewArray(arrayList) {
const combinedArray = [];
let finalGeneratedArray = [];
for(let i =0; i<= arrayList[0].length ; i++ ){
for(let j = 0; j<= arrayList[0].length; j++){
if(arrayList[j]== undefined || arrayList[j][i] == undefined ) {
break;
}
finalGeneratedArray.push(arrayList[j][i]);
}
if(finalGeneratedArray.length > 0){
combinedArray.push(finalGeneratedArray);
}
finalGeneratedArray = [];
}
return combinedArray;
}
const result = joinNewArray(finalArray);
console.log(result);
Upvotes: 0
Reputation: 11001
Combine arrays in one array and use map
. This should work even your array size increase from 3 elements to more.
const array1 = ["one", "two", "three"];
const array2 = ["1", "2", "3"];
const array3 = ["a", "b", "c"];
const array4 = ["10", "20", "30"];
const all = [array1, array2, array3, array4];
const [oneArray, twoArray, threeArray] = all[0].map((_, i) => all.map(arr => arr[i]));
console.log(oneArray);
console.log(twoArray);
console.log(threeArray);
Upvotes: 0
Reputation: 1
const array1 = ["one", "two", "three"];
const array2 = ["1", "2", "3"];
const array3 = ["a", "b", "c"];
const array4 = ["10", "20", "30"];
const newArr = [array1, array2, array3, array4]
const oneArray= newArr.map((arr) => arr[0]);
const twoArray= newArr.map((arr) => arr[1]);
const threeArray= newArr.map((arr) => arr[2]);
Upvotes: 0
Reputation: 8683
Yes, it's very simple
const array1 = ["one", "two", "three"];
const array2 = ["1", "2", "3"];
const array3 = ["a", "b", "c"];
const array4 = ["10", "20", "30"];
const oneArray = [array1[0],array2[0],array3[0],array4[0]];
const twoArray = [array1[1],array2[1],array3[1],array4[1]];
const threeArray = [array1[2],array2[2],array3[2],array4[2]];
console.log([oneArray, twoArray, threeArray])
Upvotes: 1
Reputation: 819
Use lodash:
array1 = ["one", "two", "three"];
array2 = ["1", "2", "3"];
array3 = ["a", "b", "c"];
array4 = ["10", "20", "30"];
result = _.zip(array1, array2, array3, array
This should give you:
[
["one", "1", "a", "10"],
["two", "2", "b", "20"],
["three", "3", "c", "30"]
]
Upvotes: 2