Join the Stack Overflow Community
Stack Overflow is a community of 6.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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]
share|improve this question

marked as duplicate by Oriol javascript Jan 16 at 6:25

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
Do you really mean "most efficient", or do you just mean "some way that works"? Is there something wrong with array.map(subarray => Math.min(...subarray))? – torazaburo Jan 16 at 6:20
    
@torazaburo just wondering, wouldn't that already be the most efficient way, at least algorithmically? You must look at all arrays to accumulate the mins array. You also must look at every number in each array to find a min. Thus the best conceivable runtime is O(#ofArrays * largestArrayLength). – nem035 Jan 16 at 6:24
1  
Did you copy your input from Search An Array Consisting of Sub-Arrays For the Largest Number and Return in a New Array? Just replace Math.max with Math.min. – Oriol Jan 16 at 6:26
    
@nem035 Any non-stupid way will be optimal because you need to at least read all the numbers in order to determine the minimum, and reading each number once is enough. – Oriol Jan 16 at 6:30
    
I'm sorry if my question as others ask, because I'm new here. thanks for help – Wawan Sumardi Jan 16 at 6:36
up vote 7 down vote accepted

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

ES6

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

ES5

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

share|improve this answer
    
Just for variety, I have added a ES5 version as well. If it is not required, please revert it – Rajesh Jan 16 at 6:25
    
@Rajesh thank you, but you deleted my description :) I write it again – Suren Srapyan Jan 16 at 6:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.