Picking the largest elements from multidimensional array in JavaScript



Given a multidimensional array and the task is to pick the largest elements from it in JavaScript.

The multidimensional arrays are an arrays inside an array. whenever there are arrays inside the array it will work as multidimensional array.

Following is the one-dimensional array -

const arr = ["Welcome", "to", "tutorials", "point"];
const arr = [1, 5, 12, 67, 99];

This is how the multidimensional array look like -

const array=[["Mike tyson", "Vijay"], ["ananya", "charmee"], ["Lion", "Tiger"]];

This is how we can access the elements from multidimensional array -

const array = [["Mike tyson", "Vijay"], ["ananya", "charmee"], ["Lion", "Tiger"]];

//This will access the first subarray
document.write(array[0]); // This will print ["Mike tyson", "Vijay"]

// This will access the first item in second subarray
document.write(array[1][0]); // This will print "ananya"

// This will access the second element in the third subarray
document.write(array[2][1]); // This will print "Tiger"

Using Math.max()method

We can pick the largest elements from a multidimensional array by using Math.max() method and for loop.

The Math.max() method returns the highest value number given in input parameters. And NaN if the parameters passed are not number.

document.write(Math.max(65, 45, 21));
// output: 65

document.write(Math.max("hello", "varma"));
// output: NaN

Example

In the example below, we have created a multidimensional array and an empty array that will hold all the largest numbers from every subarray. The Math.max() method will pick the largest number in each subarray. The spread(…) operator array[x] will get all the all the elements from array and make it as arguments to Math.max() method. Then the highest numbers will be pushed into an empty array.

<!DOCTYPE html>
<html>
<head>
   <title>Picking the largest elements from multidimensional array in JavaScript</title>
   <button onClick = "func()">Click!</button>
   <p id = "para"> </p>
</head>
<body>
   <script>
      const array = ([[23, 45, 22], [45, 55, 11], [66, 99, 200], [43, 76, 2022]]);
      function func(){
         function fun(array) {
            var EmpArr = []
            var x = 0;
            var len = array.length;
            for (x; x < len; x++) {
               EmpArr.push(Math.max(...array[x]))
            }
            return EmpArr;
         }
         document.getElementById("para").innerHTML = fun(array);
      };
   </script>
</body>
</html>

As we can see in the output, the highest numbers from every subarray are been pushed into the empty array.

Using forEach()method

The forEach() method calls specified function for every element in the array. And this method will not execute for empty elements.

Syntax

Following is the syntax of forEach() method -

array.forEach(function(currentValue, index, arr));

The following are the parameters of this function –

  • function, this parameter is a function that will execute on every element.

  • currentValue, the current element being processed in the array.

  • index, this parameter is the index of the current element.

  • arr, The array of the current element.

Example

In the following example, we have created a multidimensional array and an empty array to hold the highest numbers from the array. we’ve passed a callback function (arr) into forEach() method and called the forEach() on array.

The spread(…) operator will get all the elements from the array will make each element of the array as argument to Math.max(), which will pick the highest numbers. These highest numbers will be pushed into empty array.

<!DOCTYPE html>
<html>
<head>
   <title>Picking the largest elements from multidimensional array in JavaScript</title>
   <button onClick = "func()">Click!</button>
   <p id = "para"> </p>
</head>
<body>
   <script>
      const array = ([[87, 54, 76], [76, 98, 90], [12, 45, 82], [65, 98, 78]]);
      function func(){
         function fun(array) {
            var EmpArr = []
            array.forEach(function(arr){
               EmpArr.push(Math.max(...arr))
            })
            return EmpArr;
         }
         document.getElementById("para").innerHTML = fun(array);
      };
   </script>
</body>
</html>

In the output, we’ve seen that we have iterated the array with forEach() and extracted the largest numbers from the array by using Math.max().

Using apply() method

The apply() method in JavaScript, will call the described function with a given value and the arguments provided as an array or array-like objects.

To get the highest number from the array, we use Math.max() method and we can any number of arguments.

document.write(Math.max(2, 6, 12, 6));
// Output: 12 

But, when you pass an array of numbers to Math.max() function, it returns NaN

const array = [32, 65, 12, 64];
document.write(Math.max(array));
// Output: NaN

To avoid this, we use apply() method.

const array = [32, 65, 12, 64];
document.write(Math.max.apply(null, array));
//Output: 65

Using map() method

The map() method creates a new array from calling the specified function for each array element. This method only calls once for each element in the array and also it will not modify the original array.

Syntax

Following is the syntax of map() method.

array.map(function(currentValue, index, arr))

Following are the parameters of this function –

  • function, this parameter is a function which will execute on every element.

  • currentValue, the current element which being processed in the array.

  • index, this parameter is the index of current element.

  • arr, The array of the particular element.

Example

Following is the program, where we have created a multidimensional array and by using map() method we looped through each subarray and inside we have Math.max() method to pick the largest number from the array.

<!DOCTYPE html>
<html>
<head>
   <title>Picking the largest elements from multidimensional array in JavaScript</title>
   <button onClick = "func()"> Click me! </button>
   <p id = "para"> </p>
</head>
<body>
   <script>
      const array = ([[87, 54, 76], [76, 98, 90], [12, 45, 82], [65, 98, 78]]);
      function func(){
         function LargeElement(array) {
            return array.map(function(subArr) {
               return Math.max.apply(null, subArr);
            });
         }
         document.getElementById("para").innerHTML = LargeElement(array);
      };
   </script>
</body>
</html>

We have seen in the output, map() method iterated through every element in the array and picked the largest numbers with the help of Math.max().


Advertisements