【问题标题】:How to find the minimum and maximum of property values [duplicate]如何找到属性值的最小值和最大值[重复]
【发布时间】:2020-08-20 04:17:12
【问题描述】:

假设我们有一个数组

car = [
{
   id:355,
   wheels:3,
},
{
   id:3624,
   wheels:2,
},
{
   id:325,
   wheels:4,
},
{
   id:744,
   wheels:3,
},

如何找到wheels 属性的最小值和最大值?

我认为应该怎么做

我的想法是我们可以从每个对象中提取轮子的值并将其存储在一个新数组中,然后使用 sort 函数首先按(默认)字典顺序对数量进行排序,然后只需使用 array.sort((a,b) => a-b) 将它们排序之后我可以使用升序

const min = array[0]
const max = array[array.length-1]

在索引 0 处将是最小值,length-1 将是最大值。我无法从原始数组中获取值并将其存储在新数组中,我也希望有一些不同和/或更简单的方法。

【问题讨论】:

  • Math.maxMath.min 函数是可变参数。所以这里有一个简单的方法:Math.max(...car.map(c => c.wheels))Math.min(...car.map(c => c.wheels))

标签: javascript arrays


【解决方案1】:

Ciao,基本上你是对的:使用自定义排序调用 sort 函数你可以执行以下操作:

car = [
{
   id:355,
   wheels:3,
},
{
   id:3624,
   wheels:2,
},
{
   id:325,
   wheels:4,
},
{
   id:744,
   wheels:3,
}];

car.sort(function(a, b) {
   return a.wheels - b.wheels;
})
console.log(car[0])  //min
console.log(car[car.length - 1]) //max

// store in new array
let result = []
result.push(car[0])
result.push(car[car.length - 1])    

console.log(result)

【讨论】:

  • 这不是最小值/最大值。
  • Ciao @Sascha 我知道 OP 想要保留对象(在找到最小值和最大值之后)。不仅仅是车轮属性的最小值和最大值。
【解决方案2】:

使用Array#reduce。 Reduce 从这里的初始值[+inifinity, - infinity] 开始,并将这个值赋给reduce 语句中的第一个参数。通过使用[min, max],值会立即存储在这些变量中。现在数组的第一个元素将传递给 reduce 函数的第二个参数。因为我这里使用了{wheels},只有对象的这个属性才会传递给这个变量。
使用箭头函数=>,我们将整个参数 min、max 和 Wheels 转移到一个匿名函数,这里缩短了,因为我只需要返回值。
这里创建了一个数组,其中包含现在累积的最小值和最大值的最小值和最大值以及实际汽车的新值。返回值 [min,max] 被传输到下一个数组的下一步,计算再次开始。
最后,您将收到来自孔阵列的最小值、最大值。

let car = [{id:355, wheels:3}, {id:3624, wheels:2}, {id:325, wheels:4}, {id:744,wheels:3}];

let result = car.reduce(([min,max], {wheels}) =>
    ([Math.min(min,wheels), Math.max(max,wheels)]),
    [Number.POSITIVE_INFINITY ,Number.NEGATIVE_INFINITY]);

console.log(result);

【讨论】:

  • 这行得通,你能解释一下这是如何工作的吗?
  • 很好的解释,我投了赞成票!
  • 感谢您的澄清!
【解决方案3】:

试试这个:

let car = [
{
   id:355,
   wheels:3,
},
{
   id:3624,
   wheels:2,
},
{
   id:325,
   wheels:4,
},
{
   id:744,
   wheels:3,
}]
  
  console.log(Math.max.apply(Math, car.map(({wheels}) => wheels)))
  console.log(Math.min.apply(Math, car.map(({wheels}) => wheels)))

【讨论】:

  • 我遇到了一个错误,即 el 未定义
  • @ProgrammingNoobHamza 这怎么可能?我编辑了我的答案,以便您可以从我的答案本身运行代码 sn-p。
  • 你可以缩短一点:Math.min.apply(Math, car.map(({wheels}) => wheels))
  • 我之前可能犯了一个错误,你是对的,你的答案是最简单的,谢谢你,我很抱歉。
  • @Sascha 非常感谢!你的回答也很聪明!
【解决方案4】:

如果您只需要最小值和最大值。

const min_and_max = (arr) => {
      let min = arr[0]
      let max = arr[0]
      for (const i in arr){
        if (arr[i].wheels > max.wheels){
          max = arr[i]
        } else if (arr[i].wheels < min.wheels){
          min = arr[i]
        }
      }
      return [min, max]
    }

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-11
    • 2012-02-10
    • 2016-10-13
    相关资源
    最近更新 更多