如下图所示混合多个数组的最佳方式是什么,
附言:
我不知道每个数组的长度是多少
数组将包含 +10000 个元素
数组会多于3个
我已经为它制定了解决方案,但我正在寻找更好的解决方案
这是我自己的解决方案,我一直在寻找更好的主意
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);
最佳答案
您可以使用 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>
使用不同长度的数组并使用函数式编程来编写优雅的代码。
这是要运行的代码笔:https://codepen.io/matteodem/pen/mddQrwe
关于javascript - 使用 JavaScript 混合数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58876739/