Getting the largest Number of a key pair value in an Array JavaScript

825 Views Asked by At

So I'm trying to get which item has the largest number in 'size' inside the 'items' array. And print out which item as in ('item1','item2', 'item3')

let items = [
  {
    item: 'item1',
    size: 545
  },
  {
    item: 'item2',
    size: 89
  },
  {
    item: 'item3',
    size: 789
  }
]

So I tried with

let sizeMax = Math.max.apply(Math, items.map((o) => {
  return o.size;
}))
console.log(sizeMax)

but its not the ES6 way and i cant figure out how i can print the 'item' that has the largest size number out the names I've been trying with:

items.forEach((item) => {
  function arrayMax(item) {
  return items.size.reduce((h, j) => Math.max(h, j));
}
console.log(items.item)

but I cant quite figure what I'm not getting right

4

There are 4 best solutions below

0
On

let items = [
  {
    item: 'item1',
    size: 545
  },
  {
    item: 'item2',
    size: 89
  },
  {
    item: 'item3',
    size: 789
  }
]

let max = items.reduce((acc, curr) => (acc.size < curr.size ? curr : acc))

console.log('max item: ',max.item);
console.log('max size: ',max.size);

1
On

You could take a spread syntax and map a destrucured property.

let items = [{ item: 'item1', size: 545 }, { item: 'item2', size: 89 }, { item: 'item3', size: 789 }],
    max = Math.max(...items.map(({ size }) => size));

console.log(max);

For getting item of the largest size, you could reduce the array by taking the geratest size as accumulator then take the wanted property.

let items = [{ item: 'item1', size: 545 }, { item: 'item2', size: 89 }, { item: 'item3', size: 789 }],
    max = items.reduce((a, b) => a.size > b.size ? a : b);

console.log(max.item);

0
On

you can use lodash for this

lodash maxBy

_.maxBy(items, 'size');
0
On

You can combine Array.prototype.sort with array+object destructuring assignment:

let items = [{item: 'item1',size: 545},{item: 'item2',size: 89},{item: 'item3',size: 789}];

const [ {item: max} ] = items.sort((a,b) => b.size - a.size);

console.log(max);