【问题标题】:How to get lowest value from an element in Array / Angular如何从 Array / Angular 中的元素中获取最小值
【发布时间】:2020-02-21 09:54:52
【问题描述】:

我有以下数组

[
 0: {
  nameId: "041c1119"
  lastError: null
  spotId: "15808822"
  workType: "1"
 },
 1: {
  nameId: "041c1130"
  lastError: null
  spotId: "15808821"
  workType: "1"
 },
 2: {
  nameId: "041c11123"
  lastError: null
  spotId: "15808820"
  workType: "1"
 }
]

我试图获得最低的spotId 值,在这种情况下我需要获得15808820。 我将不胜感激任何建议的帮助(使用 lodash 的示例会很棒) 谢谢!

【问题讨论】:

标签: javascript angular typescript


【解决方案1】:

不需要任何像Lodash这样的外部库,你可以用纯JS来实现。

这是使用 ES6 特性和Array.reduce() 方法的一行代码的解决方案。

const data = [{
  nameId: "041c1119",
  lastError: null,
  spotId: "15808822",
  workType: "1"
}, {
  nameId: "041c1130",
  lastError: null,
  spotId: "15808821",
  workType: "1"
}, {
  nameId: "041c11123",
  lastError: null,
  spotId: "15808820",
  workType: "1"
}];


const minSpotId = data.reduce((prev, current) => (prev.spotId < current.spotId) ? prev : current);

console.log(minSpotId);

【讨论】:

    【解决方案2】:

    我建议只遍历数组并与现有的最小值进行比较:

    const data = [{
      nameId: "041c1119",
      lastError: null,
      spotId: "15808822",
      workType: "1"
    }, {
      nameId: "041c1130",
      lastError: null,
      spotId: "15808821",
      workType: "1"
    }, {
      nameId: "041c11123",
      lastError: null,
      spotId: "15808820",
      workType: "1"
    }];
    
    let minSpotId;
    
    data.forEach(el => {
      if (minSpotId === undefined || parseInt(el.spotId) < minSpotId) {
        minSpotId = parseInt(el.spotId);
      }
    });
    
    console.log(minSpotId);

    【讨论】:

      【解决方案3】:

      const data = [{
        nameId: "041c1119",
        lastError: null,
        spotId: "15808822",
        workType: "1"
      }, {
        nameId: "041c1130",
        lastError: null,
        spotId: "15808821",
        workType: "1"
      }, {
        nameId: "041c11123",
        lastError: null,
        spotId: "15808820",
        workType: "1"
      }];
      
      const lowest = Math.min.apply(Math, data.map(function(o) {
        return o.spotId
      }));
      
      console.log(lowest);

      【讨论】:

        猜你喜欢
        • 2018-07-07
        • 1970-01-01
        • 2019-01-21
        • 2019-02-23
        • 2021-11-29
        • 2021-04-10
        • 2013-06-16
        • 1970-01-01
        • 2018-01-24
        相关资源
        最近更新 更多