JC_Rambo
JC_Rambo

Reputation: 61

How to get lowest value from an element in Array / Angular

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!

Upvotes: 0

Views: 788

Answers (3)

Maniraj Murugan
Maniraj Murugan

Reputation: 9084

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

Upvotes: 3

Ian
Ian

Reputation: 1179

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

Upvotes: 1

Nick
Nick

Reputation: 16576

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

Upvotes: 1

Related Questions