如何找出嵌套数组中首元素最大的子数组并输出完整子数组?
解决方案
方法一:使用Array.reduce()直接获取目标子数组
reduce方法可以遍历数组并维护一个累积值,我们可以用它直接比较每个子数组的首元素,最终保留首元素最大的子数组:
let arr = [ [10, '0.07', ['oranges', 'with apples'], ['bananas', 'with apples']], [20, '0.15', ['oranges', 'with apples'], ['bananas', 'with apples']], [30, '0.26', ['oranges', 'with apples'], ['bananas', 'with apples']] ]; const maxSubArray = arr.reduce((prev, curr) => { // 比较当前子数组首元素和之前保存的子数组首元素 return curr[0] > prev[0] ? curr : prev; }); console.log(maxSubArray); // 输出:[30, '0.26', ['oranges', 'with apples'], ['bananas', 'with apples']]
逻辑说明:初始时prev是数组第一个子数组,之后每遍历一个子数组curr,就对比两者的首元素,把更大的那个子数组作为新的prev,遍历结束后prev就是首元素最大的子数组。
方法二:先找最大值再匹配子数组
如果你已经能获取首元素的最大值,可以用Array.find()找到对应子数组:
let arr = [ [10, '0.07', ['oranges', 'with apples'], ['bananas', 'with apples']], [20, '0.15', ['oranges', 'with apples'], ['bananas', 'with apples']], [30, '0.26', ['oranges', 'with apples'], ['bananas', 'with apples']] ]; // 先获取所有子数组首元素的最大值 const maxValue = Math.max(...arr.map(sub => sub[0])); // 找到首元素等于最大值的子数组 const maxSubArray = arr.find(sub => sub[0] === maxValue); console.log(maxSubArray); // 输出:[30, '0.26', ['oranges', 'with apples'], ['bananas', 'with apples']]
逻辑说明:先用map提取所有子数组的首元素,再用Math.max得到最大值,最后用find筛选出首元素等于该最大值的子数组。
内容的提问来源于stack exchange,提问作者masch1na
相关产品推荐
相关产品推荐

