2

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
1
  • Please show the code of your try. Commented Jun 16, 2016 at 8:11

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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]]
answered Jun 16, 2016 at 8:16

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.