What would be the most efficient way to take n smallest numbers from Array in Javascript
[[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]
Result is
[1,13,32,1]
What would be the most efficient way to take n smallest numbers from Array in Javascript
[[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]
Result is
[1,13,32,1]
Try Math.min()
. It gets numbers and returns the minimum from them. I used the map() function to iterate over each nested array, then have used Math.min()
with the ..., which will destroy the nested array and pass it to the function like Math.min(4,5,1,3)
for the first nested one
var arr = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];
var minArr = arr.map(item => Math.min(...item));
console.log(minArr);
var arr = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]];
var minArr = arr.map(function(array){
return Math.min.apply(null,array)
});
console.log(minArr);