简体   繁体   中英

Get 1 element from each javascript array concat then loop into one array

I have 4 arrays, I'd like to combine them into 1. I can do that, but I'd like to take one element from each array, push it to my new array, then get the next 4 and so on. This is what I got:

var a = [ "foo", "bar", "baz", "bam", "bun", "fun" ];
var b = [ 1, 2, 3, 4, 5, 6];
var c=["a","b","c","d","e","f"];
var d=[7,8,9,10,11,12]
var neat=[];
neat= a.concat(b, c,d);
//neat=["foo","bar","baz","bam","bun","fun",1,2,3,4,5,6,"a","b","c","d","e","f",7,8,9,10,11, 12]

The result I want would be something like this:

//neat=["foo",1,"a",7,"bar",2,"b",8...]

I'm not sure if a loop will work or if I need to use another function

Assuming each source array is the same length:

a.forEach((e, i) => {
  neat.push(e, b[i], c[i], d[i]);
};

Please try the below code :

 var a = [ "foo", "bar", "baz", "bam", "bun", "fun" ]; var b = [ 1, 2, 3, 4, 5, 6]; var c=["a","b","c","d","e","f"]; var d=[7,8,9,10,11,12] var neat=[]; //neat= a.concat(b, c,d); //neat=["foo","bar","baz","b for (var i = 0; i < a.length ; i++) { neat.push(a[i], b[i], c[i], d[i]); } console.log(neat); 

While Justins answer is correct, however if the lengths of the array are not the same every time, you could do

var maxItems = Math.max(a.length,b.length,c.length,d.length);

var neat = [];

for(var i = 0; i < maxItems; i++){

  if(a[i] != undefined){
    neat.push(a[i]);
  }

  if(b[i] != undefined){
    neat.push(b[i]);
  }

  if(c[i] != undefined){
    neat.push(c[i]);
  }

  if(d[i] != undefined){
    neat.push(d[i]);
  }
}

Math.max would find the biggest number of entries from between the 4 arrays, then a simple for loop on that number and check if the value is undefined before pushing it to neat array .

See JSFiddle

Because the length of the all arrays are equal. So we can easily do that using loop.

var a = [ "foo", "bar", "baz", "bam", "bun", "fun" ];
var b = [ 1, 2, 3, 4, 5, 6];
var c=["a","b","c","d","e","f"];
var d=[7,8,9,10,11,12]
var neat=[], i;

for(i=0;i<a.length;i++){
    neat.push(a[i]);
    neat.push(b[i]);
    neat.push(c[i]);
    neat.push(d[i]);
}
console.log(neat);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM