Locate the Highest Number within a Multi-Dimensional Array and Store it in a Fresh Array

I'm currently tackling a coding challenge that involves working with nested arrays. The task is to find the largest number in each sub-array and then create a new array containing only the largest numbers from each one. Initially, my approach was to define variables for each subarray, use a for-loop to compare values within each array, and then add the largest value to a new array. However, after implementing the first for-loop and testing my code, I noticed an unexpected result - the entire first subarray was being added to the new array. Before proceeding with additional loops, I want to identify the mistake in my code. Any insights into where I might be going wrong would be greatly appreciated. For context, this challenge is geared towards beginner JavaScript coders and it's recommended to utilize comparison operators in the solution.

function largestOfFour(arr) {
      var one = arr[0];
      var two = arr[1];
      var three = arr[2];
      var four = arr[3];
      var newArr = [];

      for (var i = 0; i < one.length; i++){
        var oneLrg = 0;
        if (one[i] > oneLrg){
          oneLrg = one[i];
          }
        newArr.push(oneLrg);
      }  

  return arr;
}

console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])); //This test case returns [4,5,1,3] instead of just [5]

Answer №1

Utilizing the comparison operator >:

var maximumsArr = [];
for(var i=0; i<inputArr.length; ++i) {           // Loop through array
  var maxVal = -Infinity;                  // Set initial maximum value
  for(var j=0; j<inputArr[i].length; ++j)        // Loop through subarrays
    if(inputArr[i][j] > maxVal)                 // Compare values
      maxVal = inputArr[i][j];                  // Update maximum value
  maximumsArr.push(maxVal);                     // Store the real maximum value
}

Using Math.max:

var maximumsArr = [];
for(var i=0; i<inputArr.length; ++i) {           // Loop through array
  var maxVal = -Infinity;                  // Set initial maximum value
  for(var j=0; j<inputArr[i].length; ++j)        // Loop through subarrays
    maxVal = Math.max(maxVal, inputArr[i][j]); // Update maximum value
  maximumsArr.push(maxVal);                     // Store the real maximum value
}

Incorporating apply:

var maximumsArr = [];
for(var i=0; i<inputArr.length; ++i)     // Loop through array
  maximumsArr.push(                      // Store ...
    Math.max.apply(Math, inputArr[i])    // ... the maximum of the subarray
  );

Employing ECMAScript 5 map,

var maximumsArr = inputArr.map(function(subarr) {
  return Math.max.apply(Math, subarr);
});

Integrating ECMAScript 5 bind,

var maximumsArr = inputArr.map(Function.apply.bind(Math.max, Math));

Alternatively, utilizing ECMAScript 6 arrow functions and spread operator,

var maximumsArr = inputArr.map(subarr => Math.max(...subarr));

Answer №2

The issue resides in the fact that you are constantly overwriting the variable oneLrg within each loop cycle, causing it to be pushed into the same loop. This results in each value being compared to 0 and eventually being saved as one[i] is greater.

To address this problem, consider implementing the following solution:

var oneLrg = 0;
for (var i = 0; i < one.length; i++){
    if (one[i] > oneLrg){
        oneLrg = one[i];
    }
}
newArr.push(oneLrg);  

Answer №3

It's no secret that myself and @Austin Hansen are both utilizing the same educational platform to tackle this challenge: Free Code Camp.

After recently completing this challenge (referred to as "Bonfires" by FCC), I wanted to share my solution that builds upon the foundation set by @Oriol's fantastic approach.

I've made a point to emphasize the importance of code blocks in my explanation, especially for newcomers like us who can struggle for hours without them : )

function largestOfFour(arr) {
 var finalArray = [];     
 for(i = 0; i < arr.length; i++) { // looping through each array
   var max = -Infinity;
   for(j = 0; j < arr[i].length; j++) { // iterating within each sub-array 
      if(arr[i][j] > max) { // comparing each element in sub-array with current max value
        max = arr[i][j]; // updating max if condition is met
      }  
    }
    finalArray.push(max); // placing this outside inner loop to avoid incorrect results
  }
  console.log(finalArray);
  return finalArray;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]], "");

https://jsbin.com/puweci/edit?js,console

Free Code Camp also acknowledges an alternative solution that doesn't utilize Array.push().

function largestOfFour(arr) {
  var results = [];
  for (var i = 0; i < arr.length; i++) {
     var max = -Infinity;
     for (var j = 0; j < arr[i].length; j++) {
        if (arr[i][j] > max) {
        max = arr[i][j];
        }
     }

    results[i] = max;
  }

  return results;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]], "");

Answer №4

This code snippet defines a function that finds the maximum of two numbers:

var greatest = function(a,b){ return Math.max(a,b); };

It then uses this function to find the maximum value in an array of numbers by applying the greatest function to each number iteratively with the

.reduce( callbackFunction, initialValue )
method:

var findMaximum = function( arr ){ return arr.reduce( greatest, Number.NEGATIVE_INFINITY ); };

The code shows another way to achieve the same result without using the greatest function by directly calling Math.max() with all the array values:

var findMaximum = function( arr ){ return Math.max.apply( Math, arr ); };

Finally, it introduces a function that takes an array (or arrays) and returns a new array containing the maximums of each inner array (using the .map( callbackFunction ) method):

var largestOfFour = function( arr ){ return arr.map( findMaximum ); };

Answer №5

It's been a while since this post was updated, but I wanted to share my unique solution to the problem at hand. Hopefully, someone will find it beneficial!

In my approach, I made use of several built-in methods such as .forEach, .sort, .push, and .shift. If you're unfamiliar with these functions, a quick search on https://developer.mozilla.org can provide more information.

function getLargestNumbers(arr) {
  var result = [];                              //create a new empty array
  arr.forEach(function(subArr){                 //iterate through the input array
    subArr.sort(function(a, b){                  //sort each subarray in descending order
      return a < b;     
    });
    result.push(subArr.shift());                 //add the largest number from each subarray to the result array
  });
  return result;                            
}

getLargestNumbers([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

Answer №6

Check out this interesting code snippet:

function findLargestNumbers(arr) {
  var newArr=[];
  largestNum=0;
  for(i=0;i<arr.length;i++)
    {
      for(j=0;j<4;j++)
        {
      if(arr[i][j]>largestNum)
        largestNum=arr[i][j];
        }
       newArr.push(largestNum);
      largestNum=0;
    }
return newArr;
}

findLargestNumbers([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

Answer №7

@orion - I had some issues with the solution you provided. The push inside the if statement was causing numbers to be added to the array that shouldn't have been there. Specifically, it was pushing [4,5] when it wasn't supposed to. To fix this, I decided to move the push outside of the for loop and also reset the lgstNumber to 0 after each iteration so it wouldn't affect the next sub-array. This adjustment worked perfectly for me...

function largestOfFour(arr) {
  // Let's get this done!
  var newArr = [];
  var lgstNumber = -  Infinity;
  for(var i = 0; i < arr.length; i++){
    for(var j = 0; j < arr[i].length; j++){
      if(lgstNumber < arr[i][j]){
        lgstNumber = arr[i][j];
      }
    }
    newArr.push(lgstNumber);
    lgstNumber = 0;
  }
  return newArr;
}

Answer №8

function findLargestNumber(arr) {
    return arr.map(function(subArray) {
        return subArray.reduce(function(firstNum, secondNum) {
            return firstNum > secondNum ? firstNum : secondNum;
        });
    });
}
findLargestNumber([[13, 27, 18, 26],[4, 5, 1, 3],[32, 35, 37, 39],[1000, 1001, 857, 1]
]);

Answer №9

It's highly efficient.

function findLargestNumbers(matrix) {

  for (var i = 0; i < matrix.length; i++) {
    for (var j = 0; j < matrix[i].length; j++) {
      matrix[i] = matrix[i].sort(function(a, b) {
        return b - a;
      });
    }
  }

  var largestNumbers = [];
  for (var k = 0; k < matrix.length; k++){
    for (var m = 0; m < matrix[k].length; m++) {
      if (m === 0) {
        largestNumbers[k] = matrix[k][m];
      }
    }
  }

  return largestNumbers;

}

findLargestNumbers([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

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

When utilizing the built-in filter in Angular 2 ag-grid, the Clear Filter button efficiently removes any text from the filter box without needing to refresh the

When using ag-Grid's default filter feature, I noticed that the clear filter button only clears the text box and does not automatically refresh the column, even when the 'clearButton' and 'applyButton' parameters are set to true. T ...

Issue with marker functionality on Google Maps JavaScript API when conditions are not functioning correctly

I am currently working on plotting different markers on Google Maps by extracting data from a CSV file. I have incorporated the parsecsv-0.4.3-beta library to read the CSV file, and everything is functioning smoothly except for when I compare two fields to ...

Using React components to create an anchor element for a popover display

Hey, I'm just starting out with React and trying to wrap my head around Hooks like useState. It's a bit challenging for me, and I want to keep things simple without making them too complex. I've encountered an issue when transitioning a Rea ...

The process of running npm build is not resulting in the creation of the bundle.js file

I've read through many Q&A threads where people are facing the same issue, but I still can't figure out what's wrong with my code. When I run 'sudo npm run build', no bundle.js file is being created.** This is my code: index ...

Trouble Logging In: User Login Issue with SailsJS and PassportJS Plugin (sails-generate-auth)

I'm currently facing an issue with user authentication in my SailsJS app using PassportJS. I followed a tutorial on setting up authentication in SailsJS using sails-generate-auth, which can be found here. The POST request seems to be routed correctl ...

What is the method for handling a get request in Spring3 MVC?

Within the client side, the following JavaScript code is used: <script src="api/api.js?v=1.x&key=abjas23456asg" type="text/javascript"></script> When the browser encounters this line, it will send a GET request to the server in order to r ...

Ways to verify the presence of an empty array object

I'm trying to determine whether all arrays inside an object are empty. To illustrate, consider the following object: var obj = { arr1: [0, 1, 2], arr2: [1, 2, 3], arr3: [2, 3, 4] }; After pop()ing values from the arrays within the object, I ...

Is the tab not displaying correctly when using Bootstrap 5 button functionality?

With Bootstrap 5, I have a modal that contains two tabs for login and register. However, I am facing an issue where the tab is not displaying correctly based on the button click. The desired behavior is that clicking on the login button should activate th ...

Steps to link two mat-autocomplete components based on the input change of one another

After reviewing the content on the official document at https://material.angular.io/components/autocomplete/examples I have implemented Autocomplete in my code based on the example provided. However, I need additional functionality beyond simple integrati ...

Verify whether an object possesses all the attributes of a class in TypeScript

Within my typescript code, I have a class called abc: export class ABC{ public a : any; public b : any; public c? : any; public d? : any; } In one of my functions, I receive an input which is represented as data:any. My goal is to verify i ...

The output type of a function given an input

Essentially, I have successfully rendered a return type for my combined reducers using the following code: const rootReducer = combineReducers({ notes: notesReducer, categories: categoriesReducer, flyout: flyoutReducer // more reducers }); export ...

Determine the active animation on an element using jQuery or JavaScript

Can you provide the code for the know_anim() function that can determine which animation is currently running on the '#div' element? Check out the jsFiddle link for reference:https://jsfiddle.net/himavicii/bL0nsjeL/ function moveLeft() ...

Checking if multiple text fields with identical names are valid using BootstrapValidator

I'm facing an issue where I am unable to validate multiple text fields with the same name. The validation only works for the first input text field, but not for the rest. <form id = "frm_org_id"> <input type="text" name="email_address[]" pla ...

Transform Image on Hover in ReactJS

I am working on a Card Component that includes an image and text. Initially, the image is redImage and the text is black. When hovering over the card, I want the redimage to change to whiteimage and the text color to change to white as well. The content ...

What is the best way to modify a particular value buried within a JavaScript object?

Within my node project, I am working with a JavaScript object like the one shown below: that.responseData = { fields: { id: { label: 'ID', value: objectRecord.id, info: '', ex ...

Manipulate a table using Jquery's find() method to insert a cell populated with information from an array using before()

My current challenge involves inserting a column of cells with data from an array. Despite attempting to use a for loop, all the cells end up displaying the same data from the array. What I really want is for each new cell to show 'row_header1', ...

Exploring the idea of how a Node.js server works

Although I have a good understanding of jQuery, I am new to modern JavaScript frameworks that have been introduced in the past few years. In the example provided, I can see how index.html functions and how server.js handles requests from it. However, I am ...

How can I best fill the HTML using React?

After attempting to follow various React tutorials, I utilized an API to fetch my data. Unfortunately, the method I used doesn't seem to be very efficient and the code examples I found didn't work for me. I am feeling quite lost on how to proper ...

The communication between socket.io encountered a net::ERR_SSL_PROTOCOL_ERROR

Here is the client code I am using: const socket = io(url); And this is the server code running on a Linux server with Express: const server = require("http").createServer(app); However, when I attempt to establish a connection, an error occurs. https:/ ...

How can we display or conceal text indicating the age of a patient based on the value returned from selectedPatient.age in a React application?

Hello, I am looking to dynamically display the age in years on the screen based on the value retrieved from selectedPatient.age, toggling between visible and hidden states. import React, { useContext } from 'react'; import { useHistory } from &ap ...