HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Function which returns the smallest / largest numbers in a nested array structure

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
smallestthearraynumbersfunctionlargestnestedstructurereturnswhich

Problem

Given is an array which contains sub-arrays. The elements in this sub-arrays are numbers.

The task is to implement a JavaScript-function which returns an array with the smallest / largest numbers in the single arrays.

I have figured out this solution:

// Returns the smallest / largest
//   numbers contained in a 
//   set of arrays.

// Parameter ---------------------
// 1.: Array - Containing other arrays.
// 2.: Function - Either Math.max or
//  Math.min

// Return -------------------------
// Array - Containing numbers in case
//  of success. 
//  Containing 'undefined' in case 
//  of elements which aren't arrays.
//  Containing NaN in case of elements 
//  which aren't numbers.

function getExtrema(structure, funct) {

  var ret = structure.map(function(value) {
    if (Array.isArray(value)) {
      return funct.apply(null, value);
    }
  });

  return ret;
}


Complete code (with examples) on CodePen: http://codepen.io/mizech/pen/bEBMaW?editors=101

Are there better ways to solve the described task?

Solution

I shoudn't be able to think to this elegant and concise solution by myself! Notably because till now I didn't pay great attention to some of the acute features of JS.

So it was for me the opportunity to examine them deeper. From this I notice a possible little improvement, by slightly reducing the code, like this:

function getExtrema(structure, funct) {

  var ret = structure.map(function(value) {
    if (Array.isArray(value)) {
      return funct(...value);
    }
  });

  return ret;
}


Here is the working modified example: http://codepen.io/anon/pen/obYMmQ?editors=101.

Code Snippets

function getExtrema(structure, funct) {

  var ret = structure.map(function(value) {
    if (Array.isArray(value)) {
      return funct(...value);
    }
  });

  return ret;
}

Context

StackExchange Code Review Q#115401, answer score: 2

Revisions (0)

No revisions yet.