如何生成与subArr长度一致的对应位置最大值数组?
问题:提取数组对应位置的最大值
现有products数组,每个元素包含subArr(你代码中写为numArr)数组属性,需返回一个与subArr长度一致的数组,其中每个元素是所有对象subArr对应位置的最大值。
示例数组
const products = [ { name: "car", subArr: ["4", "200", "599.4", "4444"] }, { name: "tv", subArr: ["44477", "50", "579.2", "3232"] }, { name: "glass", subArr: ["2121.1", "6347", "8867", "90.01"] } ];
期望输出
[44477, 6347, 8867, 4444]
你的尝试代码问题分析
你当前的代码已经完成了对应位置数值的提取和转换,但最终返回的是二维数组(每个位置对应一个数值数组),没有对每个位置的数值数组取最大值,因此无法得到目标结果。
修改后的解决方案
const products = [ { name: "car", numArr: ["4", "200", "599.4", "4444"] }, { name: "tv", numArr: ["44477", "50", "579.2", "3232"] }, { name: "glass", numArr: ["2121.1", "6343", "8867", "90.01"] } ]; function getMaxFromArr(products) { if (!products.length) { return []; } // 以第一个元素的numArr长度为基准遍历每个位置 return products[0].numArr.map((_, index) => { // 提取所有产品对应位置的数值并转为数字 const positionNums = products.map(prod => parseFloat(prod.numArr[index])); // 取出当前位置的最大值 return Math.max(...positionNums); }); } const result = getMaxFromArr(products); console.log("result", result); // 输出: [44477, 6343, 8867, 4444]
关键修改说明
- 在
map回调中新增Math.max(...positionNums),对每个位置的数值数组取最大值,将二维数组转为一维结果数组 - 保留空数组判断,避免空输入导致报错
如果需要让结果保持字符串格式(与原数据类型一致),可以将最大值转为字符串:
return Math.max(...positionNums).toString();
此时输出为["44477", "6343", "8867", "4444"],更贴合原数据格式。
内容的提问来源于stack exchange,提问作者FD3
相关产品推荐
相关产品推荐

