首页 > 解决方案 > 如何从 Array / Angular 中的元素中获取最小值

问题描述

我有以下数组

[
 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 的示例会很棒)谢谢!

标签: javascriptangulartypescript

解决方案


不需要任何像 Lodash 这样的外部库,您可以在纯 JS 中实现结果。

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

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


推荐阅读