I have an array array like this
[
[
"text1",
"text2",
"text3",
"text4",
"text5"
],
[
"Rtext1",
"Rtext2",
"Rtext3",
"Rtext4",
"Rtext5"
],
[
"1",
"2",
"3",
"4",
"5"
]
]
I need to convert it in to the following format using JavaScript
[
[
"text1",
"Rtext1",
"1"
],
[
"text2",
"Rtext2",
"2"
],
[
"text3",
"Rtext3",
"3"
],
[
"text4",
"Rtext4",
"4"
],
[
"text5",
"Rtext5",
"5"
]
]
What is the best way to accomplish this using JavaScript or jQuery?
I used multiple for loops to loop through the array but couldn't get the hang of it.
Pranav C Balan
115k25 gold badges173 silver badges195 bronze badges
asked Jun 16, 2016 at 8:09
Jagan K
1,0573 gold badges16 silver badges39 bronze badges
-
Please show the code of your try.str– str2016年06月16日 08:11:07 +00:00Commented Jun 16, 2016 at 8:11
3 Answers 3
Use Array#forEach method
var data = [
[
"text1",
"text2",
"text3",
"text4",
"text5"
],
[
"Rtext1",
"Rtext2",
"Rtext3",
"Rtext4",
"Rtext5"
],
[
"1",
"2",
"3",
"4",
"5"
]
];
var res = [];
data.forEach(function(ele) {
ele.forEach(function(v, i) {
res[i] = res[i] || []; // define inner array if not defined
res[i].push(v); // push value to array
})
});
console.log(res);
answered Jun 16, 2016 at 8:13
Pranav C Balan
115k25 gold badges173 silver badges195 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Here is how you do it..
var x = [
[
"text1",
"text2",
"text3",
"text4",
"text5"
],
[
"Rtext1",
"Rtext2",
"Rtext3",
"Rtext4",
"Rtext5"
],
[
"1",
"2",
"3",
"4",
"5"
]
];
var a = x[0];
var b = x[1];
var c = x[2];
var finalAra = [];
for(var i=0;i<a.length;i++){
var temp = [];
temp.push(a[i]);temp.push(b[i]);temp.push(c[i]);
finalAra.push(temp);
}
console.log(finalAra);
answered Jun 16, 2016 at 8:13
Tirthraj Barot
2,6792 gold badges20 silver badges33 bronze badges
Comments
Sounds like you're doing array zipping. This is pretty common in functional programming, and there's even a builtin in Underscore.js to do it for you, if you already use the library or have no need to reimplement the functionality.
_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
// => [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]
Comments
lang-js