Javascript - 在对象数组的对象中找到最大值

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

我有一个包含对象数组的对象。我试图在不手动遍历数组和对象的情况下找到对象 属性、'sortOrder' 的最大值。

所以我的变量如下所示:

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}
 ]
};

所以我会尝试遍历它以最终找到最高的 sortOrder 33。不一定是数组索引或包含它的对象,只是数字。

谢谢

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);

(我不得不稍微更正您的输入数据:数组不包含您显示的索引号。)

最简单的是将对象中的两个数组合并为一个列表,然后用reduce求最大值:

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
    }
  ]
};


let allPeople = [...myObj.people, ...myObj.otherPeople];

let max = allPeople.reduce((maxSort, person) => {
  return Math.max(maxSort, person.sortOrder)
}, 0));

console.log(max)

您可以按最高的 sortOrder 对它们进行排序,然后取每个数组中最高的元素:

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
    }
  ]
};
Object.values(myObj).forEach(peopleArray => {
  peopleArray.sort((a, b) => b.sortOrder - a.sortOrder)
})
let maxValue = Math.max(myObj.people[0].sortOrder, myObj.otherPeople[0].sortOrder)
console.log(maxValue)

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}
]};

let maxSortOrder = 0;
for (const value of Object.values(myObj)) {
    maxSortOrder = value.reduce((acc, { sortOrder }) => sortOrder > acc ? sortOrder : acc, maxSortOrder);
};

console.log(maxSortOrder); //33