0

I have the following Array

[
 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"
 }
]

I'm trying to get the lowest spotId value, in this case I would need to get 15808820. I will appreciate any help of advice ( an example using lodash would be awesome) Thanks!

German Quinteros
  • 1,870
  • 9
  • 33
JC_Rambo
  • 61
  • 7
  • 2
    Does this answer your question? [Compare JavaScript Array of Objects to Get Min / Max](https://stackoverflow.com/questions/8864430/compare-javascript-array-of-objects-to-get-min-max) – Ivar Feb 21 '20 at 01:15
  • 1
    `arr.reduce((prev, curr) => prev.spotId < curr.spotId ? prev : curr).spotId` – Ivar Feb 21 '20 at 01:17

3 Answers3

2

No need of any external library like Lodash, you can achieve the result in pure JS.

Here is the solution with one line code using ES6 features with Array.reduce() method.

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);
Ivar
  • 6,138
  • 12
  • 49
  • 61
Maniraj Murugan
  • 8,868
  • 20
  • 67
  • 116
1

I would recommend just iterating through the array and comparing to an existing min value:

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);
Nick
  • 16,066
  • 3
  • 16
  • 32
1

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);
Ian
  • 1,198
  • 1
  • 5
  • 15