Locate the maximum and minimum elements from within each nested array using JavaScript

Here is an array I'm working with:

var arr = [[12,45,75], [54,45,2],[23,54,75,2]];

I am trying to determine the largest and smallest elements in this nested array:

The minimum value should be: 2

while the maximum should be: 75

I attempted using the following functions but they did not yield the correct results:

    function Max(arrs)
    {
        if (!arrs || !arrs.length) return undefined;
        let max = Math.max.apply(window, arrs[0]), m,
            f = function(v){ return !isNaN(v); };
        for (let i = 1, l = arrs.length; i<l; i++) {
            if ((m = Math.max.apply(window, arrs[i].filter(f)))>max) max=m;
        }
        return max;
    }
    function Min(arrs)
    {
        if (!arrs || !arrs.length) return undefined;
        let min = Math.min.apply(window, arrs[0]), m,
            f = function(v){ return !isNaN(v); };
        for (let i = 1, l = arrs.length; i<l; i++) {
            if ((m = Math.min.apply(window, arrs[i].filter(f)))>min) min=m;
        }
        return min;
    }

Unfortunately, these functions incorrectly identify the maximum as 75 and the minimum as 12.

If you have any suggestions or guidance, please feel free to share.

I have also explored other solutions on Stack Overflow but none seem to address my specific issue.

The response provided at Merge/flatten an array of arrays in JavaScript? tackles merging arrays instead of performing operations while maintaining the original array structure.

Answer №1

Utilizing ES6 features

const numbers = [[12,45,75], [54,45,2],[23,54,75,2]];

const maxNumber = Math.max(...[].concat(...numbers));

const minNumber = Math.min(...[].concat(...numbers));

console.log(maxNumber);

console.log(minNumber);

Answer №2

To start, flatten the array initially (benefit - suitable for nested arrays at different levels)

var flatArray = [[12,45,75], [54,45,2],[23,54,75,2] ].toString().split(",").map(Number);

Next, find the minimum and maximum values within the flattened array

var maxVal = Math.max.apply( null, flatArray );
var minVal = Math.min.apply( null, flatArray );

Check out this working example:

var flatArray = [
  [12, 45, 75],
  [54, 45, 2],
  [23, 54, 75, 2]
].toString().split(",").map(Number);

var maxVal = Math.max.apply(null, flatArray);
var minVal = Math.min.apply(null, flatArray);

console.log(maxVal, minVal);

Answer №3

UPDATE 2024

Retrieve the minimum or maximum value from a flat array by spreading its values.

const
    values = [[12, 45, 75], [54, 45, 2], [23, 54, 75, 2]],
    flat = values.flat(),
    min = Math.min(...flat),
    max = Math.max(...flat);

console.log(min);
console.log(max);

An ES5 recursive method is used for deep nested arrays.

var array = [[12, 45, 75], [54, 45, 2], [23, 54, 75, 2]],
    min = array.reduce(function getMin(a, b) {
        return Math.min(Array.isArray(a) ? a.reduce(getMin) : a, Array.isArray(b) ? b.reduce(getMin) : b);
    }),
    max = array.reduce(function getMax(a, b) {
        return Math.max(Array.isArray(a) ? a.reduce(getMax) : a, Array.isArray(b) ? b.reduce(getMax) : b);
    });
    
console.log(min, max);

Functions are provided for use as callback functions.

function flat(f, v) { return Array.isArray(v) ? v.reduce(f) : v; }
function getMin(a, b) { return Math.min(flat(getMin, a), flat(getMin, b)); }
function getMax(a, b) { return Math.max(flat(getMax, a), flat(getMax, b)); }

var array = [[12, 45, 75], [54, 45, 2], [23, 54, 75, 2]],
    min = array.reduce(getMin),
    max = array.reduce(getMax);
    
console.log(min, max);

Answer №4

To simplify the process, you can combine all the nested arrays into one single array and then determine the minimum and maximum values by using Math.min.apply(null, array) and Math.max.apply(null, array)

var arr = [[45,76,33], [15,29,46],[10,5,30,8]];
var mergedArray = [].concat.apply([], arr);
var maxVal = Math.max.apply(null, mergedArray);
var minVal = Math.min.apply(null, mergedArray);
console.log(maxVal, minVal)

Answer №5

This solution provides a method to find the maximum value in a nested array without using concatenation, making it suitable for arrays with any level of nesting.

let arr = [[12,45,75], [54,45,2],[23,54,75,2]];

function findMaxFromNestedArray(arr) {
  let max = Number.MIN_SAFE_INTEGER;
  
  for (let item of arr) {
    if(Array.isArray(item)) {
      let maxInChildArray = findMaxFromNestedArray(item);
      if (maxInChildArray > max) {
        max = maxInChildArray;
      }
    } else {
      if (item > max) {
        max = item;
      }
    }
  }
  
  return max;
}

console.log(findMaxFromNestedArray(arr))

Answer №6

A single solution using reduce method:

const findMaxMin = (mergedArr) => {
return mergedArr.reduce(
        (prev, curr) => {            
            return {
                max: Math.max(curr, prev.max),
                min: Math.min(curr, prev.min),                
            };
        },
        {
            max: -Infinity,
            min: Infinity,            
        }
    );
}
const mergeArrays = arr => [].concat(...arr)
const result = findMaxMin(mergeArrays(arr))
console.log(result);

Answer №7

To simplify the array, we can utilize Array.prototype.flat. Visit this link for more information.

const nestedArray = [[12,45,75], [54,45,2],[23,54,75,2]]
const flattenedArray = nestedArray.flat(2)

const minValue = Math.min.apply(null, flattenedArray)
const maxValue = Math.max.apply(null, flattenedArray)

console.log( {flattenedArray, minValue, maxValue} )

Answer №8

function flattenArray(arr) {
  return arr.join().split(',').map(Number);
}

function getMaxValue(arr) {
  const flatArr = flattenArray(arr);
  let maxVal = flatArr[0];
  flatArr.forEach((value) => {
    maxVal = value > maxVal ? value : maxVal;
  });
  return maxVal;
}

function getMinValue(arr) {
  const flatArr = flattenArray(arr);
  let minVal = flatArr[0];
  flatArr.forEach((value) => {
    minVal = value < minVal ? value : minVal;
  });
  return minVal;
}

const array1 = [
  [12, 45, 75],
  [54, 45, 2],
  [23, 54, 75, 2],
]
console.log(`Max: ${getMaxValue(array1)}`);
console.log(`Min: ${getMinValue(array1)}`);

const array2 = [1, 2, [14, 56, 34, [48, 98]], [14, 16, 11, [18, 81]], 34, 35];
console.log(`Max: ${getMaxValue(array2)}`);
console.log(`Min: ${getMinValue(array2)}`);

Answer №9

Here are 3 straightforward methods to handle this:

Imagine you possess a complex nested array:

let numbers = [12, 44, [33, 94, 10444], 104]

Start by flattening the array. There exist multiple ways to achieve this, but let's focus on 2 of the simplest techniques:

const flat = numbers.flat() // 12, 44, 33, 94, 10444, 104 
const flat = [].concat(...numbers) // 12, 44, 33, 94, 10444, 104 

Next, it's a breeze - finding the minimum and maximum values from the flattened array:

const min = Math.min(...flat) // 12
const max = Math.max(...flat) // 10444

Alternatively, you can organize the flattened array, then fetch the first and last elements:

flat.sort((a,b) => {return a-b}) // 12, 33, 44, 94, 104, 10444
const min = flat.shift() // 12
const max = flat.pop() // 104444

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The issue with angular JavaScript in the child component is causing the left side navigation dropdown to malfunction

I'm currently facing an issue with the left side navigation in my home component. The dropdown functionality is not working within one of the routing modules (admin-routing.module.ts). Interestingly, the navigation works perfectly fine in app-routing. ...

Guide to writing a Jasmine test case to verify Toggle class behavior within a click event

My directive is responsible for toggling classes on an element, and it's working as expected. However, I seem to be encountering an issue with the jasmine test case for it. // Code for toggling class fileSearch.directive('toggleClass', func ...

Rearrange Firebase data on the client side

Having trouble sorting data in Firebase for a web project. I tried using orderByChild to filter the data, but now I need to also order it by date. Here's what I've attempted: Tried using object.values with .sort, no luck Attempted to use lodas ...

Obtain abbreviated names for the days of the week starting from Monday to Sunday using JavaScript

Is there a way to retrieve the abbreviated names of each day of the week in JavaScript, starting from Monday through Sunday? ...

Tips for adjusting line placement on a leaflet map

My leaflet map displays two lines, but sometimes they appear identical, causing the map to show only one line due to overlap. To address this issue, I am attempting to shift one of the lines slightly so that both are visible on the map. One method I cons ...

Leveraging TipTap.dev for building a joint editing platform -

I have integrated the collaboration feature from tiptap.dev into my NextJS application. Initially, I used their CLI command for the Hocuspocus server which worked well on port 1234 locally and synchronized text editing across browsers seamlessly. However, ...

The React Bootstrap modal is encountering an error, specifically a TypeError where it is unable to read properties of undefined, specifically the 'classList'

Every time I try to open a modal, an error pops up saying "TypeError: Cannot read properties of undefined (reading 'classList')." I'm unsure about how to resolve this issue. Here is the code for the specific modal and the button that trigger ...

Best method for filling forward NaN values within a numpy array

Illustrative Case To demonstrate, let's examine the numpy array arr as provided below: import numpy as np arr = np.array([[5, np.nan, np.nan, 7, 2], [3, np.nan, 1, 8, np.nan], [4, 9, 6, np.nan, np.nan]]) The represen ...

Exploring data elements in a Javascript array

Is there a way to use Javascript or jQuery to address the individual employee number, tasks, and sites in the following JSON array? $.each(mySchedule, function(i, obj) { console.log(obj.employees); }); var mySchedule = { "schedule": { "empl ...

Is there a way to store the outcome of an HTTP GET call in Angular 7 as a JSON file?

Hey there! I'm currently working on a web app that needs to make regular calls to a remote API. Since the response will always be consistent, I am planning to optimize the site's performance by storing the response data in a local JSON file. This ...

How to Toggle the :invalid State to True on a Dropdown Element Using JQuery

$("#select_id").is(':invalid') false Is there a way to change it to true? $("#select_id").addClass(':invalid'); $("#select_id").prop('invalid',true) Unfortunately, this method does not seem t ...

What method can we use to temporarily route traffic from one URL to another URL for a specific amount of time?

Is there a way to use javascript/jquery code that will redirect my website to a different domain, but only during specific hours? I'm looking to have the redirection occur between 2 a.m. and 4 a.m., so that it only works for two hours out of the day. ...

Exploring the Differences Between Javascript Ajax Response and String Comparisons

I'm having trouble comparing the result of an ajax call with a string. The ajax call is returning the correct result, but I'm struggling to get the if statement to properly compare it with my string. Any suggestions on how to approach this? ...

Ways to determine if a new set of input values duplicates previous rows in an array

My form has an array of input fields. Is there a way to validate each row's inputs and ensure that they all have at least one unique value in any field, preventing identical rows? For example, the 2nd row should only be allowed to have a maximum of ...

Steps for eliminating an element upon the second click:

I am faced with a challenge where I need to dynamically add elements to a container on the first click and delete them on the second click. I feel like I am complicating things unnecessarily and there must be a simpler and more elegant solution available. ...

What is the most effective way to obtain the final row of a Google DataTable using JavaScript?

I have data for Temperature, Humidity, and Time that I can retrieve from a database table to use in a DataTable. However, I also want to extract the most recent set of values from the DataTable and display them in console.log. After attempting to output c ...

Using Python3, transform a bytes object containing hexadecimal ASCII representation into an ASCII string

Is there a way to convert a variable with Ascii data in a bytes object to a string in Python3? For example: a = bytearray(b'31303031') I would like to convert it to: '1001' Any suggestions on how to achieve this in Python3? ...

Setting the selected value of a static select menu in Angular 2 form

I'm having an issue with my Angular 2 form that includes a static select menu. <select formControlName="type" name="type"> <option value="reference">Referentie</option> <option value="name">Aanhef</option> &l ...

Display all the names of the files from various file inputs in a unified notification

I have developed a function that checks if the selected file names already exist in the database. It currently alerts a message for each file name found in the database, which can be overwhelming with multiple files. I am looking for suggestions on how t ...

Avoid mutating the prop directly and instead, utilize a data or computed property that is based on the value of the prop. The prop that is being mutated in this case is

Help me understand this issue that Vue is displaying, I am not sure what is going on. This is my progress element: <el-progress :percentage="percentCompleted" v-show="uploadingVideo"></el-progress> data() { return{ percentCompleted: 0 ...