What is the best way to extract the biggest number from every sub-array in JavaScript?

How can I find and return the largest numbers from each subarray within a multidimensional array, resulting in an array of these largest numbers?

For instance: array = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]

The expected output would be: [ 5, 27, 39, 1001 ]

I attempted this solution:

function largestOfFour(arr) {

  for(var i = 0; i < arr.length; i++) {
    large = 0;
    for(var j = 0; j < arr[i].length; j++) {
      if(arr[i][j] > large) {
        large = arr[i][j];
      }
    }
  }
  return arr.push(large);
}

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

However, only the largest number from the first subarray is being returned (5)

Answer ā„–1

After carefully analyzing the code, I have successfully reached a final solution. The initial loop is used to go through the larger array, while the second loop iterates over the elements of the subarray. A conditional statement inside checks for the largest number.

function findLargestNumbers(arr) {
  var result = [];
  for(k=0;k<arr.length;k++){
     var largestNum = 0;
       for(i=0;i<arr[k].length;i++){
          if(largestNum<arr[k][i]) {
              largestNum=arr[k][i];
          }
       }
   result.push(largestNum);
   }
  return result;
}

Answer ā„–2

Finally, I have found the solution to my query

function highestInEachArray(arr) {
  var newArray = [];
  for (index=0; index<arr.length; index++) {
    var highestNum = 0;
    for (innerIndex=0; innerIndex<arr[index].length; innerIndex++) {
      if (arr[index][innerIndex] > highestNum) {
        highestNum = arr[index][innerIndex];
      }
    }
    newArray.push(highestNum);
  }
  // Success awaits you!
  return newArray;
}

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

Answer ā„–3

To implement a basic loop, you will need to set up an array where the results can be stored and then push the values into that array. It seems like in your current code, you are only pushing one item at the end (return arr.push(large)).

I trust this explanation is helpful.

Best regards,

Lisa

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

Breaking apart a string that consists of boolean values

Presented below is a JavaScript function function cmd_parse( cmd ) { return cmd.split( /\s+/ ); } For instance, when calling the function like this words = cmd_parse("hello jay true"); The output would be words[0]="hello" words[1]="jay" wor ...

The size of Bootstrap 3 columns adjusts dynamically based on the width of the window as the page is being

I am facing an issue with the layout of my bootstrap site when resizing the 3 horizontal columns based on the window size upon page load. Currently, I have a script that adjusts the height of each column to match the tallest one so they appear uniform whe ...

What is the best method for retrieving logs from one Cloud Function to another?

I am attempting to access and review the logs produced by my cloud functions. After reviewing the Firebase Documentation, I discovered a CLI command that allows us to accomplish this task: firebase functions:log This particular command displays all of the ...

Acquire a structured list of the focus order within the DOM elements

It intrigues me how the DOM is constantly changing. I'm curious if there's an easy way to retrieve a sorted list of focusable elements within the DOM at any moment. This would encompass nodes with a specified tabindex value that isn't -1, as ...

Incorrect script enqueue order in child theme of WordPress

Help needed with enqueuing a script in a WordPress child theme. Despite specifying Jquery dependency, the script is loaded before Jquery. The code in question: add_action( 'wp_enqueue_scripts', 'child_theme_scripts' ); function child_ ...

The selected checkbox model does not update its value when checked

I have created checkboxes in a View using ViewModel with bool properties. I am currently facing an issue where the query in the controller always jumps to the "else statement" even if the checkbox for "Month" has been checked. The value for Month is always ...

Employ the 'strictNullChecks' flag for a single function or method

I am working with the following method implementation: remove(node: SortedQueueNode<V, K>) : SortedQueueNode<V, K>{ // ... return node.parent; } In this function, there are several points where it returns a value, and I want to en ...

Using Asynchronous JavaScript and XML (AJAX) to make calls to a web service

My program is showing an internal server error var parameters = "<?xml version='1.0' encoding='utf-8'?>" + "<soap:envelope xmlns:xsi='ttp://www.w3.org/2001/xmlschema-instance' xmlns:xsd='http://www.w3. ...

Is there a way to obtain the function associated with an onclick attribute?

I have a function attached to the onclick event in the HTML, as shown below: <script> function f1(){ alert('hello world'); }; </script> <a onclick="f1()">test</a> I want to manipulate that function by binding it to ...

Populate MySQL database with values from various arrays

Looking for guidance on updating a table with data from arrays generated by a webform. I need to populate columns 'surname' and 'ref' but am unsure how to handle arrays efficiently. In this case, [0] corresponds to the database ID, [1] ...

Express js is failing to deliver static assets

Hello, I'm having an issue with Express Js. It seems like a beginner problem - static files are not being served properly. const express = require('express'); express() .set('view engine','ejs') .use(express.stat ...

"Implementing database updates with AJAX and utilizing the PUT method: a step-by-step guide

I am attempting to update a database property named "Estado" using ajax. Here is the code I am using: function updateDatabaseProperty(idMarker, newState) { $.ajax ({ url: `/api/IgnicoesAPI/${idMarker}`, type: 'PUT ...

What is the advantage of not importing related modules?

As a newcomer to React, please excuse any novice questions I may have. I am currently utilizing npx create-react-app to develop a React app, but I'm unsure of the inner workings: Q1-If I were to throw an error in a component like so: import React, { ...

Using Asp.net MVC to Serialize a Json Array

Can anyone assist me? I am trying to code the 'Shippings' class as an Array in order to achieve the following JSON structure: { "seller_id": "123", "amount": 100, "order": { "order_id": "1111", "sales_tax": 0, "product_type": ...

What is the best way to automatically add a space every four digits in an input field using JavaScript?

How can I format a card number input field so that it displays spaces after every 4 digits when the customer enters the full 16-digit number? <input type="text" id="input-number" placeholder="e.g 1234 5678 9123 0000"> ...

Tips for iterating through an array of objects nested within other objects

Good afternoon everyone, Iā€™m having trouble accessing the attributes of a JavaScript object array through AJAX. Can anyone spot where I might be going wrong? View image description This is my AJAX call: $("#cbx1").on("change", func ...

if the arguments for a javascript function are not provided

Currently, I am in the process of learning JavaScript through a book called "Visual Quickstart Guide". However, I have encountered a challenge with understanding the logic behind a particular code snippet. In the function definition below, it appears that ...

Having trouble with the "foreach" binding in knockout where the "html" binding buttons are not functioning properly in Javascript

I'm experiencing an issue with the following code: <html lang="en"> <head> <link href="css/bootstrap.min.css" rel="stylesheet"> </head> <body> <script type='text/javascript' src='knockout-3. ...

Preserve the current slide in JavaScript even after the page is refreshed

I have implemented a JavaScript slide that contains a gridview. My goal is to maintain the current slide even after a postback or page refresh, as each gridview serves a different function. Here is an excerpt of my code: Html: <div class = "callbacks ...

using javascript to change a link's state with a click action

I have a question that is related to the topic discussed here: Making a link stay active displaying hover effect upon click using javascript. I am looking for a way to disable the active class when the same link is clicked again. Any assistance on this mat ...