How can I split an array into two arrays with alternating elements

  • A+
Category:Languages

I want to split an array of strings into two arrays. However, when I push the strings into the new arrays, it should be alternating. So, if the array is:

let alph = [a,b,c,d,e,f] 

Then the new arrays would look like:

firstArr = [a,c,e] secondArr = [b,d,f] 

How can I do it so I'm not repeating myself? I have the following code, and it works, but I do not want to write two of the same filter functions (keep things DRY):

let firstArr = alph.filter((letter, index) => {   return index % 2 === 0; }) 

 


You could take an array of the both arrays and take the index as indicator for the wanted array for pushing.

let alph = ['a', 'b', 'c', 'd', 'e', 'f'],     first = [],     second = [],     temp = [first, second];      alph.forEach((v, i) => temp[i % 2].push(v));  console.log(first); console.log(second);

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: