5

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]
  • 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))`? –  Jan 16 '17 at 06: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 '17 at 06: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](http://stackoverflow.com/q/31094820/1529630)? Just replace `Math.max` with `Math.min`. – Oriol Jan 16 '17 at 06: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 '17 at 06:30
  • I'm sorry if my question as others ask, because I'm new here. thanks for help –  Jan 16 '17 at 06:36

1 Answers1

7

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);
Community
  • 1
  • 1
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112