如何从多维数组中获取每个索引的最大值-javascript

问题描述 投票:0回答:2

这是我第一次面对多维数组。所以我有这样的年份数组

yearArr = [
  [2019, 2018, ''],
  [2019, 2018, 2017],
  ['', 2018, 2017]
]

我需要做的是,我需要制作一个固定年份数组,例如

newYearArr = [ 2019, 2018, 2017 ]

这是我所做的

var highestValue = []

for(var i = 0; i < yearArr[0].length; i++){
           highestValue.splice(i,0,0)
           for(var j = 0; j < yearArr.length; j++){
             if(yearArr[i][j] > highestValue[i]){
               highestValue[i] = yearArr[i][j]
             }
           }
       }

但它总能带来回报

newYearArr = [2019, 2019, 2019]
javascript multidimensional-array
2个回答
0
投票

索引处的数组项目为空或全部相同,因此您可以对其进行迭代,并在索引处尚不存在的项目的索引处分配给组合数组:

const yearArr = [
  [2019, 2018, ''],
  [2019, 2018, 2017],
  ['', 2018, 2017]
];
const newYearArr = [];
yearArr.forEach((years) => {
  years.forEach((year, i) => {
    if (!newYearArr[i]) {
      newYearArr[i] = year;
    }
  });
});
console.log(newYearArr);

0
投票

从您的问题的标题开始,我希望您希望结果为[2019, 2019, 2018],而不是[2019, 2018, 2017],因为这些是每个子数组中的最大值。假设Math.max很方便:

var newYearArr = yearArr.map(function(subarray) {
    return math.max.apply(Math, subarray);
});

实时示例:

var yearArr = [
  [2019, 2018, ''],
  [2019, 2018, 2017],
  ['', 2018, 2017]
];
var newYearArr = yearArr.map(function(subarray) {
    return Math.max.apply(Math, subarray);
});
console.log(newYearArr);

或使用ES2015 +:

const newYearArr = yearArr.map(subarray => Math.max(...subarray));

实时示例:

const yearArr = [
  [2019, 2018, ''],
  [2019, 2018, 2017],
  ['', 2018, 2017]
];
const newYearArr = yearArr.map(subarray => Math.max(...subarray));
console.log(newYearArr);

0
投票

您可以将-Infinity取为非数字,并获得每个索引位置的最大值。

const getNumber = v => typeof v === 'number' ? v : -Infinity;
var yearArr = [
  [2019, 2018, ''],
  [2019, 2018, 2017],
  ['', 2018, 2017]
],
    result = yearArr.reduce((r, a) => a.map((v, i) => Math.max(getNumber(v), getNumber(r[i]))), []);

console.log(result);
© www.soinside.com 2019 - 2024. All rights reserved.