在 JavaScript 中从数组数组中获取最小数组
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/11 10:52:17
假设,我们有一个像这样的嵌套数组 −
const arr = [ ["LEFT", "RIGHT", "RIGHT", "BOTTOM", "TOP"], ["RIGHT", "LEFT", "TOP"], ["TOP", "LEFT"] ];
我们需要编写一个接受这样一个数组的 JavaScript 函数。然后函数应该选择最小的子数组(所含元素数量最小)并返回它。
示例
其代码为 −
const arr = [
["LEFT", "RIGHT", "RIGHT", "BOTTOM", "TOP"],
["RIGHT", "LEFT", "TOP"],
["TOP", "LEFT"]
];
const findShortest = (arr = []) => {
const res = arr.reduce((acc, val, ind) => {
if (!ind || val.length < acc[0].length) {
return [val];
};
if (val.length === acc[0].length) {
acc.push(val);
};
return acc;
}, []);
return res;
};
console.log(findShortest(arr));
输出
控制台中的输出将是 −
[ [ 'TOP', 'LEFT' ] ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

