简体   繁体   English

如何将数组拆分为具有交替元素的两个数组

[英]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): 我有以下代码,它可以工作,但我不想写两个相同的过滤器函数(保持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); 

Since filter creates one array, you need two, or use eg forEach 由于filter创建一个数组,您需要两个,或使用例如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) 

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: 要稍微清理它,你可以使用箭头函数并使它们成为1个衬里,然后在过滤器函数中传递它们,如:

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

you can use reduce for this : 你可以使用reduce来:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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