Wil*_*ham 1 javascript arrays ecmascript-6
能否请您推荐更优雅的处理这些案例的方法?
const arr1 = [1, 2, 3];
const arr2 = ['a', 'b', 'c'];
const getCombinations = () => {
const combinations = [];
arr1.forEach(el1 => {
arr2.forEach(el2 => {
combinations.push({
el1,
el2
});
});
});
return combinations;
};
console.log(getCombinations());Run Code Online (Sandbox Code Playgroud)
您可以使用Array.flatMap()具有Array.map():
const arr1 = [1, 2, 3];
const arr2 = ['a', 'b', 'c'];
const getCombinations = (a, b) =>
a.flatMap(el1 => b.map(el2 => ({ el1, el2 })));
const result = getCombinations(arr1, arr2);
console.log(result);Run Code Online (Sandbox Code Playgroud)