Skip to content
Advertisement

Javascript – find highest value in an object of arrays of objects

I have an object containing arrays of objects. I’m trying to find the highest value of an object property, ‘sortOrder’ without manually iterating through the arrays and objects.

So my variable looks like this following:

const myObj = {
 people: [
   0: {firstname: 'Dave', lastName: 'Jones', sortOrder: 22},
   1: {firstname: 'Jane', lastName: 'Smith', sortOrder: 11}
 ],
 otherPeople: [
   0: {firstname: 'Jen', lastName: 'SomeLastName', sortOrder: 33},
   1: {firstname: 'ExampleFirstName', lastName: 'ExampleLastName', sortOrder: 12}
 ]
};

So I’d be trying to iterate through this to eventually find, in this case, the highest sortOrder of 33. Not necessarily the array index or the object containing it, just the number.

Thanks

Advertisement

Answer

const myObj = {
  people: [ {firstname: 'Dave', lastName: 'Jones', sortOrder: 22}, {firstname: 'Jane', lastName: 'Smith', sortOrder: 11} ],
  otherPeople: [ {firstname: 'Jen', lastName: 'SomeLastName', sortOrder: 33}, {firstname: 'ExampleFirstName', lastName: 'ExampleLastName', sortOrder: 12} ]
};

const maxSortOrder = 
  Object.values(myObj)
  .flat()
  .reduce((max, { sortOrder = 0 }) => sortOrder > max ? sortOrder : max, 0);

console.log(maxSortOrder);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement