Most efficient method for organizing a nested array (comparing output versus sorting and using math.max)

I have always wondered if it is possible to retrieve a returned value from a nested function or code block.

For instance, consider the scenario where you want to sort values in an array from largest to smallest using the .sort() method and then extract the largest value from each nested array and add it to a new array:


function largestOfFour(arr) {
  for (var i = 0; i < arr.length; i++) {
    console.log(arr[i]);
    arr[i].sort(function(a,b) {
      return b - a; // attempt to access this organized array here
    });
    var newArr = [];
    newArr.push(arr[i][0]);
  }
}

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

Answer №1

Sorting the array is not necessary in this case. One could simply utilize the Math.max method.

function findLargestNumbers(arr) {
  return arr.map(function (el) {
    return Math.max.apply(null, el);
  });
} // [ 5, 27, 39, 1001 ]

Check out the DEMO here

Answer №2

Is this the correct way?

function findLargestNumbers(arrays) {
  var finalResults = [];
  for (var index = 0; index < arrays.length; index++) {
    console.log(arrays[index]);
    arrays[index].sort(function(a, b) {
      return b - a; // aim is to access this newly sorted array
    });
    finalResults.push(arrays[index][0]);
  }
  return finalResults;
}

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

Answer №3

Is it feasible to retrieve a returned value from a function/code block nested within another code block?

The only way to obtain the return value is by calling the function. Since you are not directly invoking the .sort callback, but rather it is executed within .sort, retrieving its return value is not possible.


I assume your inquiry stems from encountering unexpected behavior in your code. Upon reviewing your script, it seems evident that although you are sorting the array, you are not utilizing it post-sorting. As mentioned earlier in my comments, your method of using .sort and accessing the largest value is correct.

To address this issue, I suggest declaring newArr outside the loop and returning it from the function:

function largestOfFour(arr) {
  var newArr = [];
  for (var i = 0; i < arr.length; i++) {
    arr[i].sort(function(a, b) {
      return b - a;
    });
    newArr.push(arr[i][0]);
  }
  return newArr;
}

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

Alternatively, there is a more concise approach that avoids mutating the input array:

function largestOfFour(arr) {
  return arr.map(function(innerArray) {
    return innerArray.reduce(function(a, b) {
      return a > b ? a : b;
    });
  });
}

Answer №4

Arranging values in an array from largest to smallest using the .sort() method, then extracting the largest value from nested arrays and placing it into a new array:

Consider utilizing a combination of while loop, .push(), .sort(), .reverse(), and largestOfFour function which can provide two arrays. The first array contains the largest number from each sub-array, while the second array comprises sorted sub-arrays from largest to smallest.

function largestOfFour(arr) {
  var res = [], i = arr.length - 1;
  while(i > -1) {
    res.push(Math.max.apply(Math, arr[i].sort(function(a, b) {
      return Number(b) - Number(a)})
      )); 
  --i;
  };     
  return [res, arr.reverse()]
}

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

function largestOfFour(arr) {
  var res = [], i = arr.length - 1;
  while(i > -1) {
    res.push(Math.max.apply(Math, arr[i].sort(function(a, b) {
      return Number(b) - Number(a)})
      )); 
  --i;
  };     
  return [res, arr.reverse()]
}

document.getElementsByTagName("pre")[0]
.textContent = JSON.stringify(largestOfFour(input), null, 2);
<pre></pre>

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

Obtaining the latest state within the existing handler

In my React application, I have a handler that shuffles the state entry data: state = { data:[1,2,3,4,5] }; public handleShuffle = () => { const current = this.state.data; const shuffled = current .map((a: any) => [Math.random() ...

The code is nearly identical except for one issue that causes an infinite loop within useEffect

Hey, I'm new to reactjs and I've encountered a puzzling situation with the following two code snippets. I can't figure out why using the "First code" results in an infinite loop (endless '123' log outs in my browser console) while ...

Encountering a "Evaluation Failed" error while scraping YouTube data with Puppeteer and Node.js

As I attempt to scrape the YouTube headline and link from a channel using Puppeteer, I encounter an Evaluation Error presenting the following message: Error: Evaluation failed: TypeError: Cannot read properties of null (reading 'innerText') a ...

Avoid nesting a VirtualizedList component inside a basic ScrollView in React Native to prevent issues

I have come across this question multiple times, and I've gone through all the suggested solutions. Most advise against nesting it inside ScrollView and recommend using SafeAreaView or another alternative instead. However, my scenario is a bit differe ...

Having trouble with your jQuery animation on a div?

Check out this jsFiddle example: http://jsfiddle.net/uM68j/ After clicking on one of the links in the demo, the bar is supposed to smoothly slide to the top. However, instead of animating, it immediately jumps to the top. How can I modify the code to ac ...

Utilizing SequelizeJS to Pass an Array of Values

I am currently exploring the possibility of passing an array as the value for the property of an instance. In my model, I have set the dataType to STRING and I am inserting values from jQuery fields into an array which I then parse from the body and assign ...

Tips on excluding an object dynamically from the chaining process in JavaScript

In my object structure, both utils and utils.not have the same prototype with an exist method. To keep it simple, here is a clearer version: var negative = true; if(negative){ //when negative===true, I want to run exist() through not object tests.util ...

Is there a way to halt or end an interval within a function triggered by useEffect()?

I am currently working on a countdown timer script using react.js. The timer displays a 3 or 5 seconds countdown before starting, with data for these countdowns coming from another component. I am facing an issue with controlling the main countdown timer ...

Using JavaScript to dynamically populate form fields

I am currently working on developing a form that allows users to add additional fields themselves. They will have the ability to add up to 5 new "options", with each option containing up to 50 "variants". For example, an option could be "size" with varian ...

Is it possible to retrieve the vertices array from a QuickHull instance in three.js?

I'm currently working on generating a geometry using QuickHull from a THREE Mesh. However, it seems that the QuickHull object only contains information pertaining to the Faces of the mesh. Does anyone know if there is a way to access the vertex infor ...

Refresh the Morris chart using jQuery after a .NET MVC post request

In my .NET Controller action, I have written code to fetch specific time zone and group data based on that time zone. The code looks like this: [HttpPost] [ActionName("FetchTimeZone")] public ActionResult FetchTimeZone(string timeZone) ...

Error: Unable to retrieve REACT JS due to a Type Mismatch

As I develop my application, I encountered an issue while attempting to sign up a user with a correct email address such as [email protected]. It resulted in a TypeError: Failed to fetch. Strangely, when I input an invalid email like "user", the proce ...

Creating a versatile Nuxt build that can be used across multiple environments

In the development of my Nuxt application, I am faced with the task of setting up two distinct environments - staging and production. Besides these, the local environment is also considered as staging. As part of this setup, I need to create specific comma ...

Using Angular directive with ng-class to display or hide element

I am trying to implement a feature in my directive template where an element is shown or hidden on mouseenter. Below is the code for my directive: angular.module('myApp') .directive("addToRoutes",['$http', '$timeout', functio ...

Is it possible to display the command output in Grunt as it runs?

When I run this command, I am not seeing any output and it runs endlessly: grunt.registerTask('serve', function () { var done = this.async(); grunt.util.spawn({ cmd: 'jekyll', args: ['serve'], ...

Array shuffled randomly

I need to connect a list of words with corresponding instructions, but I want the order of the words to be random. For example, if I have pairs like (cat, forget) and (dog, remember), the word should always be followed by its matching instruction, but the ...

Angular Router malfunctioning, URL is updated but the page fails to load properly

My file structure is shown below, but my routing is not working. Can you please help me identify the issue? index.html <!DOCTYPE html> <html ng-app="appNakul"> <head> <title> Nakul Chawla</title> <!--<base href ...

Finding the offsetWidth (or similar measurement) for a list item (LI) element

Can jQuery be used to determine the width of an element? alert($("#theList li:eq(0)").offsetWidth); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ol id="theList"> <li>The quick brown ...

Unable to establish a new pathway in the index.js file of a Node.js and Express website running on Heroku

I recently made some changes to my index.js file: const express = require('express'); const path = require('path'); const generatePassword = require('password-generator'); const fetch = require('node-fetch'); const ...

Incorporating JSON data into React JS and performing operations on it

Just started delving into the world of React and currently focusing on learning the basics of syntax. I've hit a roadblock while trying to make AJAX requests for data display. An error in the console indicates that the local version of test.json cann ...