Discover the highest number within an array made up of multiple arrays

JavaScript Challenge:

function findLargestInEachSubArray(arr) {


var maxValue = 0;
var largestNumbers = [];

for(var i = 0; i < arr.sort().reverse().length; i++){
  for(var j = 0; j < arr[i].length; j++){

    if(maxValue < arr[i][j]){
      maxValue = arr[i][j]; // issue here
      //largestNumbers.push(maxValue);  this will only add the first element in each subset
      // result [4,5,13,27,32,35,37,39,1000,1001]
    }

  }
}

return largestNumbers;

}

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


//  Expected Outcome:

// [5, 27, 39, 1001]

I'm stuck on this problem. How can I modify my function to correctly find and store the biggest number from each sub-array into the largestNumbers array using nested for-loops?

Answer №1

Considering your preference for a for loop:

const findLargestOfFour = (arr) => {
  let largestNumbers = [];
  for(let index = 0; index < arr.length; index++) {
    largestNumbers[index] = arr[index].sort((a,b) => b - a)[0];
  }
  return largestNumbers;
}

This function will sort the subarrays and extract the largest number from each one.

Answer №2

Consider using the map() function as an alternative to traditional for loops.

var array = [[8, 11, 3, 7], [15, 29, 20, 28], [38, 43, 45, 47], [2000, 2001, 1857, 12]]

function findMaxInArray(data) {
  return data.map(element => Math.max.apply(null, element))
}
console.log(findMaxInArray(array))

Answer №3

Utilizing the spread syntax with Math.max can simplify your code.

function maxValueFromArray(data) {
    return data.map(arr => Math.max(...arr))
}

var numbers = [[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]

console.log(maxValueFromArray(numbers));

Answer №4

Perhaps not the most efficient solution, but this code should get the job done

function findLargestInEachArray(arr) {
   return arr.map(function (subArr) {
      return Math.max.apply(null, subArr);
      // return Math.max(...subArr);
   });
}

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

Answer №5

When dealing with arrays and sub array items of significant size, this approach appears to be the most effective.

let arr = [[14, 5, 11, 33], [3, 17, 22, 16], [62, 25, 57, 89], [10001, 1901, 887, 11]],
    result = arr.map(array => array.reduce((previous,current) => previous > current ? previous : current));
console.log(result);

Answer №6

I approached the problem in this manner, ensuring it handles both negative and positive numbers effectively.

function findLargestInArrays(arr) {
  var maxValues = [];
  for(let i = 0; i < arr.length ; i++){
    let maxValue = -10000000;
    for(let j = 0; j < arr[i].length; j++)
      if(arr[i][j] > maxValue)
         maxValue = arr[i][j];
      
    maxValues[i] = maxValue;
  }
console.log(maxValues)

  return maxValues;
}

findLargestInArrays([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
findLargestInArrays([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]);
findLargestInArrays([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]])

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

Sort through a list of objects using the criteria from a separate array

Looking to apply a filter on an array of objects: const myArray = [{ id: 4, filters: ["Norway", "Sweden"] }, { id: 2, filters :["Norway", "Sweden"] }, { id: 3, filters:["Denmark", "Sweden&q ...

Invoking WinJS.Binding.List.createFiltered with an asynchronous call to the predicate function

Is there a way to wait for the async operation in this code snippet and use its result as the predicate instead of always returning false? return someList.createFiltered(function(item) { var filter = false; var ...

implementing a method event within a JavaScript class

Within the wapp.js file, there is a JavaScript class defined as follows: function Wapp() { this.page = function($page_name) { this.onLoad = function($response) { } } this.navigate = { changePage: function(link) { ...

Here's a step-by-step guide on how to parse JSON information in JavaScript when it's formatted as key-value

I need to parse the JSON data in JavaScript. The data consists of key-value pairs. Data looks like this: {09/02/2014 15:36:25=[33.82, 33.42, 40.83], 08/11/2014 16:25:15=[36.6, 33.42, 40.45], 07/30/2014 08:43:57=[0.0, 0.0, 0.0], 08/12/2014 22:00:52=[77.99 ...

Meteor is only returning a portion of the values from the child array

I have a list structured as follows: { _id: xKdshsdhs7h8 files: [ { file_name : "1.txt", file_path : "/home/user1/" }, { file_name : "2.txt", file_path : "/home/user2/" } ] } Currently, I ...

What could be causing my directive to not display the String I am trying to pass to it?

Currently attempting to create my second Angular directive, but encountering a frustrating issue. As a newcomer to Angular, I have been studying and referencing this insightful explanation as well as this helpful tutorial. However, despite my efforts, I am ...

Adjusting images of various sizes within a single row to fit accordingly

I am faced with a challenge of aligning a set of images on a webpage, each with varying heights, widths, and aspect ratios. My goal is to arrange them in a way that they fit seamlessly across the screen while ensuring their heights are uniform. Adjusting ...

show.bs.modal event does not trigger within a bootstrap 4 modal that is loaded externally

I am trying to implement a feature where a common modal dialog can be loaded into any page from an external file. While the functionality works, I am facing an issue where the show.bs.modal and hide.bs.modal events are not triggered when the modal markup i ...

Is there a way to efficiently manage open browser tabs using Protractor?

I attempted to follow the recommendations provided in this article How to close a browser tab in Protractor without closing the entire browser in order to close a new tab in Chrome and navigate back to the main application. Unfortunately, the first sugge ...

How to Align Text and Image Inside a JavaScript-Generated Div

I am attempting to use JavaScript to generate a div with an image on the left and text that can dynamically switch on the right side. What I envision is something like this: [IMAGE] "text" Currently, my attempt has resulted in the text showing ...

C: inserting new item into an array that was dynamically allocated

Searching for a solution on Google has been unsuccessful so far. I couldn't find anything helpful, and it seems like what I'm doing is correct. Most of the information I found about passing dynamically allocated arrays through a function involves ...

Using jQuery to generate columns depending on the quantity of occurrences of an element inside a specific Div

I've encountered a challenge while using a plugin that restricts access to the HTML, but allows for adding CSS and Javascript. I am aiming to achieve the following: Determine if a specific class within a div is active If it's 'active' ...

Toggle between light and dark mode with React

I am in the process of creating a simple dark/light toggler button using React. Currently, I have developed a toggler component with a state defined as: this.state = {style: './App.css'} I have also created two functions – one that changes thi ...

When using PHP submit, the text input from dynamically generated JS fields is not being posted

My HTML form includes a table of text inputs that I intend to use for generating an SQL INSERT query. The issue I am facing is that my manually inputted table has 5 text inputs, with the option for users to add more. The additional input fields are being c ...

Beginners guide to initializing a character array within a struct

What is the correct way to initialize a character array in a C# structure? I am trying this: struct cell { public char[] domain = new char[16]; public int[] Peers; public int NumberOfPeers; public char assignValue; } However, I am receivi ...

Is Angular considered bad practice due to its reliance on singletons, despite its widespread use and popularity?

Angular relies on singletons for all its services, however using singletons is often frowned upon in the development community. Despite this controversy, I personally find Angular to be a valuable and effective tool. What am I overlooking? ...

Transferring arrays from Laravel's controller to the view

Currently, I am working with arrays in Laravel and I need a solution to access specific values and present them as form fields in a blade.php file. Here is an example of the array structure: $postData = array( 'source_addr' => &ap ...

What are the advantages of using history.push or another method from react-router-dom compared to simply assigning the path to window.location.pathname?

When I need to navigate within my code, I find it more convenient to simply assign the desired path to window.location.pathname. Can this approach have any drawbacks? ...

Converting data into a multidimensional array in AngularJS: A comprehensive guide

Struggling to convert a JSON array into a multidimensional array, looking for some guidance. I attempted using _.groupBy in underscore.js, but it's not proving successful with the nested array. If there is any way to convert from the given data [{ ...

Encountered a console error when attempting to execute a sample React JS web application

I recently started exploring React JS and decided to experiment with a simple "hello react" web application. However, when I tried to run it, I encountered the following error in the console. Warning: Calling Element.createShadowRoot() for an element that ...