Home > OS >  How to find the sum of values inside nested arrays and push to new array (JavaScript)
How to find the sum of values inside nested arrays and push to new array (JavaScript)

Time:01-27

The problem is on leetcode.com, and is # 1672: "Richest Customer Wealth"

Problem text:

"You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th​​​​ bank. Return the wealth that the richest customer has.

A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth.

Example 1:

Input: accounts = [[1,2,3],[3,2,1]]
Output: 6
Explanation:
1st customer has wealth = 1 2 3 = 6
2nd customer has wealth = 3 2 1 = 6
Both customers are considered the richest with a wealth of 6 each, so return 6."*

I'm trying to take the numbers inside of a nested array and push them through to a new array. Once I am able to accomplish this, I can use the sort and slice method on the new array to return the highest value of the new array, but I can't seem to get the nested arrays to add up correctly.

Example 1: [[1,2], [3,4], [5,6]] is expected to return [3, 7, 11], which I would sort / splice to return 11, but the new array only returns [3].

Example 2: [[1,2,3], [3,2,1]] expected to return [6, 6], but only returns [6].

I believe the issue is that the for loop is not iterating through the entire array for some reason, and is only returning the value of the first nested array.

/**
 * @param {number[][]} accounts
 * @return {number}
 */
const maximumWealth = (accounts) => {
    let total = 0;
    let totalArr = [];
    for (i = 0; i < accounts.length;   i) {
        if (Array.isArray(accounts[i])) {
            total  = maximumWealth(accounts[i]);
            totalArr.push(total);
            console.log(totalArr);
        } else {
            total  = accounts[i];
        }
    }
    return total;
};

When printing totalArr to the console from console.log(totalArr); it is only returning the value of the first nested array.

CodePudding user response:

You're not summing each nested array. Use this to get the total of each account. Get the maximum of the result after calling this.

function sumArrays(accounts) {
    return accounts.map(account => {
        let total = 0;
        account.forEach(val => total  = val);
        return total;
    });
}

console.log(sumArrays([[1,2], [3,4], [5,6]]));
console.log(sumArrays([[1,2,3], [3,2,1]]));
To get the maximum, combine that with a call to Math.max().

    function sumArrays(accounts) {
        return accounts.map(account => {
            let total = 0;
            account.forEach(val => total  = val);
            return total;
        });
    }
    
    function maximumWealth(accounts) {
      let totals = sumArrays(accounts);
      return Math.max(...totals);
    }

    console.log(maximumWealth([[1,2], [3,4], [5,6]]));
    console.log(maximumWealth([[1,2,3], [3,2,1]]));

CodePudding user response:

There's a much easier way: map your initial array to reduced arrays of the totals and then use Math.max to find out the max amount.

const addNumbersInArray = (arr) => {
  return arr.reduce((acc, value) => acc   value)
}

const maximumWealth = (accounts) => {
  const addedNumbers = accounts.map(addNumbersInArray);
  return Math.max(...addedNumbers);
};

console.log({
  '[[6,2,3], [3,2,4]]': maximumWealth([[6,2,3], [3,2,4]])
})

  • Related