kentor kentor - 3 months ago 5
Javascript Question

Get three lowest values from Array

Assuming I got an JSON Object like this:

{"27":[2300,2300,2700,2300,2300,2300,2500,2300,2700,2300,2300,2300,2700,2300,2700,2300,2300,2300,2300,1900,2700,2300,2300,2300]}


I want to get the three lowest values from this array and store it as another array. I have tried
sort()
but experienced that it considers 10000 lower than 1300 for example.

Question: How would I get the three lowest value from the above JSON object and store it as an own array?

This is how I have tried to sort my array:

-prices[searchLog.PriceSearchId].sort();

Answer

Try this.

var prices = {
  "27": [2300, 2300, 2700, 2300, 2300, 2300, 2500, 2300, 2700, 2300, 2300, 2300, 2700, 2300, 2700, 2300, 2300, 2300, 2300, 1900, 2700, 2300, 2300, 2300]
};
var leastThree = prices["27"].sort(function(a, b) {
  return a - b;
}).slice(0, 3);
console.log(leastThree);

Comments