簡體   English   中英

如何將數組拆分為具有交替元素的兩個數組

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

我想將一個字符串數組拆分成兩個數組。 但是,當我將字符串推入新數組時,它應該是交替的。 所以,如果數組是:

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

然后新的數組看起來像:

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

我怎么能這樣做,所以我不重復自己? 我有以下代碼,它可以工作,但我不想寫兩個相同的過濾器函數(保持DRY):

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

您可以獲取兩個數組的數組,並將索引作為推送所需數組的指示符。

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

由於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) 

為了更好的可讀性,為這些提供單獨的過濾功能沒有任何問題。 要稍微清理它,你可以使用箭頭函數並使它們成為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);

你可以使用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