6

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

4 Answers 4

13

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

Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

1

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

Comments

0

you can use reduce for this :

const alph = ['a', 'b', 'c', 'd', 'e', 'f'];

const result = alph.reduce((acc, letter, ndx) => {
  acc[ndx % 2] = acc[ndx % 2] || [];
  acc[ndx % 2].push(letter);
  return acc;
}, []);

const [firstArr, secondArr] = result;

console.log(firstArr, secondArr);

Comments

Your Answer

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.