0

I´m new to Javascript, I´m trying to filter an array of objects through one of the object properties (to get the object that has the biggest value of said property. How would I go about to doing that?

Just to clarify, this is an example, imagine the three "amount" properties have different values, and I want to get the biggest one:

let object = {
    names: name,
    amount: 3,
}

let objectArray = [object, object, object];

I tried to use the .filter() method, but don´t know how to apply it to a property like I want to

Bas H
  • 2,114
  • 10
  • 14
  • 23
Zeke Cachi
  • 49
  • 4

2 Answers2

1

Probably a duplicate of: Return object with highest value

Solution adapted from above:

Assuming you have three objects in an object array:

let object1 = {
    names: "Object 1",
    amount: 3,
};

let object2 = {
    names: "Object 2",
    amount: 4,
}

let object3 = {
    names: "Object 3",
    amount: 5,
}

let objectArray = [object, object2, object3];

Then using reduce you can get the object with the largest amount:

const objectWithLargestAmount = objectArray.reduce((max, object) => max.amount > object.amount ? max : object);

leaves you with the following object

{
  amount: 5,
  names: "Object 3"
}
Roshaan
  • 11
  • 3
0

First you can use Math.max method to determine the maximum amount, then you can use Array#filter method to return only the objects with the maximum amount already determined.

const 
      input = [ { names: 'Peter', amount: 6 }, { names: 'James', amount: 60 }, { names: 'Andrew', amount: 300 }, { names: 'Thomas', amount: 20 }, { names: 'Judas', amount: 2000 }, { names: 'John', amount: 11 } ], 
      
      maxAmount = Math.max( ...input.map(o => o.amount) ),
      
      output = input
        .filter(({amount}) => amount === maxAmount);

console.log(output);
PeterKA
  • 24,158
  • 5
  • 26
  • 48