Reputation: 61
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
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
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
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