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!

2
  • 2
    Does this answer your question? Compare JavaScript Array of Objects to Get Min / Max Commented Feb 21, 2020 at 1:15
  • 1
    arr.reduce((prev, curr) => prev.spotId < curr.spotId ? prev : curr).spotId Commented Feb 21, 2020 at 1:17

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.