0

I am trying to access the maximum profit made by this company in a nested structure and I cannot get Math.max() to do it for me. I have tried using let and also just copying and pasting the numbers into a statement and it will not work. I thought by using Math.max() and inserting the path to the profit within the parentheses it would do so. Can anyone explain to me how to do this or what I am doing wrong. See code below

let company = {
  name: 'Apple, Inc',
  founded: 1976,
  financials: {
    incomeStatement: {
      years: [2020, 2019, 2018],
      revenue: [125, 120, 115],
      costs: [100, 100, 100],
      profit: [25, 20, 15]
    },
    balanceSheet: {
      years: [2020, 2019, 2018],
      assets: [200, 190, 180],
      liabilties: [100, 95, 90],
      equity: [100, 95, 90]
    },
    cashFlow: {
      years: [2020, 2019, 2018],
      operating: [75, 65, 55],
      investing: [22, 20, 18],
      financing: [-94, -80, -75]    
    }
  },
  competitors: ['Microsoft', 'Amazon', 'Samsung']
}

console.log(company.name);
console.log(company.competitors);
console.log(Math.min(company.financials.incomeStatement.profit));
console.log(company.competitors[2]);
console.log(company.financials.incomeStatement.years);
console.log(company.financials.incomeStatement.revenue[0]);

I am trying to access the maximum profit made by this company in a nested structure and I cannot get Math.max() to do it for me. I have tried using let and also just copying and pasting the numbers into a statement and it will not work. I thought by using Math.max() and inserting the path to the profit within the parentheses it would do so. Can anyone explain to me how to do this or what I am doing wrong. The console keeps saying NaN or either property not defined. See code below

1 Answers1

1

To get the maximum value from an existing array you can use Math.max.apply():

let maxProfit = Math.max.apply(null, company.financials.incomeStatement.profit);
console.log(maxProfit);

Here's a working example:

let company = {
  name: 'Apple, Inc',
  founded: 1976,
  financials: {
    incomeStatement: {
      years: [2020, 2019, 2018],
      revenue: [125, 120, 115],
      costs: [100, 100, 100],
      profit: [25, 20, 15]
    }
    // other data omitted for brevity...
  }
}

let maxProfit = Math.max.apply(null, company.financials.incomeStatement.profit);
console.log(maxProfit);
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • ... or `Math.min(...company.financials.incomeStatement.profit)`, or `Math.max()` if that's in fact what's desired. – Pointy Jun 11 '23 at 13:25