Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
})
like image 666
flored27 Avatar asked Jun 28 '18 20:06

flored27


Video Answer


3 Answers

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);
like image 83
Nina Scholz Avatar answered Oct 16 '22 16:10

Nina Scholz


Since filter creates one array, you need two, or use e.g. forEach

var arr = ["a","b","c","d","e","f"], firstArr = [], secondArr = [];

arr.forEach( (a,i) => {
  (i % 2 === 0) ? firstArr.push(a) : secondArr.push(a);
})

console.log(firstArr)
console.log(secondArr)
like image 20
Asons Avatar answered Oct 16 '22 15:10

Asons


For better readability there's nothing wrong with having separate filter functions for these. To clean it up a little you could use arrow functions and make them 1 liners and then pass them in the filter function, like:

const alpha = ['a', 'b', 'c', 'd', 'e', 'f'];
const filterByEvens = (letter, index) => index % 2 === 0;
const filterByOdds = (letter, index) => index % 2 !== 0;
const evens = alpha.filter(filterByEvens);
const odds = alpha.filter(filterByOdds);
like image 1
Ashley Avatar answered Oct 16 '22 16:10

Ashley