Jagan K
Jagan K

Reputation: 1057

How to change array format in javascript

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.

Upvotes: 2

Views: 1532

Answers (3)

boxmein
boxmein

Reputation: 875

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]]

Upvotes: 0

Tirthraj Barot
Tirthraj Barot

Reputation: 2679

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

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115222

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

Upvotes: 1

Related Questions