yudistira nugraha
yudistira nugraha

Reputation: 193

How to get max value of each index from multi dimentional array - javascript

This is my first time facing multidimensional array.

I have an array of year like this:

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

I need to make a fix year array like:

newYearArr = [ 2019, 2018, 2017 ]

The value at index 0 is the highest value at index 0 of any of the arrays, the value at index 1 is the highest at index 1, etc.

This is what I have done:

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]
             }
           }
       }

but it always returns

newYearArr = [2019, 2019, 2019]

Upvotes: 1

Views: 138

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386560

You could take -Infinity for not numbers and get the maximum for each index position.

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

console.log(result);

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370679

The array items at an index are either empty or all the same, so you can iterate over them and assign to the combined array at that index of an item at the index doesn't exist yet:

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);

Upvotes: 1

Related Questions