【问题标题】:Determin Highest Value on Array of Objects [duplicate]确定对象数组的最大值[重复]
【发布时间】:2021-09-13 07:28:26
【问题描述】:

我有这个问题,对象数组被有意放入这种结构中:

const productArray = [
  { 'Product A': 5000 },
  { 'Product B': 2500 },
  { 'Product C': 3500 },
  { 'Product D': 2750 },
  { 'Product E': 1500 },
];

我可以通过什么方式确定这种数组的最高值和最低值?非常感谢。

【问题讨论】:

  • 使用不同的结构可能会更好。要么使用具有不同属性的单个对象,要么使用具有值的数组。或者,将产品名称及其值作为单独属性的对象数组。拥有一个对象数组,其中每个对象都有不同的属性,这会让您自己的生活变得不必要地困难。
  • @ivar 我希望是这样。但是问题是故意放在这个结构中的。

标签: javascript arrays object


【解决方案1】:

对数组进行排序,最小的排在最前面,最大的排在最后

const productArray = [
  { 'Product A': 5000 },
  { 'Product B': 2500 },
  { 'Product C': 3500 },
  { 'Product D': 2750 },
  { 'Product E': 1500 },
];
const sortedProduct = productArray.sort((a, b) => Object.values(a)[0] - Object.values(b)[0]);
console.log(sortedProduct);
console.log('Lowest value ', sortedProduct[0]);
console.log('Highest value ', sortedProduct[sortedProduct.length - 1]);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-25
  • 1970-01-01
  • 1970-01-01
  • 2017-12-31
  • 1970-01-01
相关资源
最近更新 更多