3 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超3個(gè)贊
您可以使用 lodash 作為您的解決方案。
const { flow, zip, flatten, filter} = _
const doTheMagic = flow(
zip,
flatten,
filter
)
const one = [1, 2, 3]
const two = ['??', '??', '??', '??', '??', '??']
const three = ['foo', 'bar', 'wow', 'okay']
const result = doTheMagic(one, two, three)
console.log(result)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>
處理不同長度的數(shù)組,并利用函數(shù)式編程來編寫優(yōu)雅的代碼。
這是一個(gè)要運(yùn)行的代碼筆:https ://codepen.io/matteodem/pen/mddQrwe

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超5個(gè)贊
let a1 = [1, 2, 3, 4, 5];
let a2 = ["??", "??", "??", "??", "??", "??"];
let a3 = ['one', 'two', 'three', 'four', 'five'];
const doTheMagic = arrayOfArrays => {
let maxLength = 0;
let result = [];
for (arr in arrayOfArrays) {
maxLength = Math.max(maxLength, arrayOfArrays[arr].length);
}
for (let i = 0; i < maxLength; i++) {
for (let j = 0; j < arrayOfArrays.length; j++) {
if (arrayOfArrays[j][i]) {
result.push(arrayOfArrays[j][i]);
}
}
}
return result;
}
console.log(doTheMagic([a1, a2, a3]));

TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個(gè)贊
這是我自己的解決方案,我正在尋找更好的主意
import { compact, flattenDeep } from "lodash/array";
export const doTheMagic = master => {
const longest = master.reduce((p, c, i, a) => (a[p].length > c.length ? p : i), 0);
const mixed = master[longest].map((i, k) => {
return master.map((o, a) => {
if (master[a][k]) return master[a][k];
});
});
const flaten = flattenDeep(mixed);
return compact(flaten);// to remove falsey values
};
const one = [1,2,3];
const two = ['a','b','c','d','e'];
const three = ['k','l','m','n'];
const mix = doTheMagic([one,two,three]);
console.log('mix: ', mix);
添加回答
舉報(bào)