Ariana A
Ariana A

Reputation: 67

How to find the maximum value of each subarray in an array and then group them into a new array

How to find the maximum value of each subarray in an array and then group them into a new array?

For example:

[1, 2, [3, 4]]//return[2, 4]
[1000, [1001, 857, 1]]//return[1000, 1001]
[[4, 5, 1, 3], 2 , 6 ,[1000, [1001, 857, 1]]]//return[5, 6, 1000, 1001]

Upvotes: 1

Views: 70

Answers (2)

Alex G
Alex G

Reputation: 1917

Try this out:

const a = [1, 2, [3, 4]];
const b = [1000, [1001, 857, 1]];
const c = [[4, 5, 1, 3], 2 , 6 ,[1000, [1001, 857, 1]]];

const max = (array) => {

    const a1 = [];
    const a2 = [];

    array.forEach((a) => (a instanceof Array) ? a1.push(max(a)) : a2.push(a));

    a1.push(Math.max(...a2));

    return a1.reduce((acc, val) => acc.concat(val), []).sort((a, b) => a - b);
};

console.log(max(a));
console.log(max(b));
console.log(max(c));

Upvotes: 6

mshouman
mshouman

Reputation: 384

function max(arr) {
  var result = [];
  arr = arr.sort();
  result.push(arr[arr.length - 1]);
  var i = 0;
  while (typeof arr[i] === 'object') {
      (function () {
          var subArr = arr[i].sort();
          var maxResult = max(subArr);
          result.push(maxResult);
          i++;
      }());
  }
  return result;
}

Upvotes: 0

Related Questions