JavaScript method not properly sorting the last nested array

I am having trouble with sorting the last nested array using arr[i].sort(). Despite trying various methods such as FOR and WHILE loops along with different operators, I still cannot achieve the desired result. Can someone help me identify what I am doing wrong? The goal is to return the largest numbers in the arrays.

function findLargestNumbers(arr) {
  var i = 0;
  while (i != arr.length) {
    arr[i] = arr[i].sort().pop();
    i++;
  }
  return arr;
}

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

Answer №1

By default, when using the sort() method, the elements are ordered as strings instead of numbers. This can lead to unexpected results, such as "1001" < "817". To achieve a numeric sort, a comparison function that performs numerical ordering needs to be provided.

function findLargestNumber(arr) {
  var i = 0;
  while (i != arr.length) {
    arr[i] = arr[i].sort(function(a, b) {
        return a - b;
    }).pop();
    i++;
  }
  return arr;
}

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

Answer №2

Although not the root cause of the issue you are encountering (as answered by @Barmar), an alternative method is using Array.map in combination with Math.max.apply to determine the maximum number in each list:

function largestOfFour(arr) {
   return arr.map(function(list) {
      return Math.max.apply(null, list);
   });
}

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

An even more concise approach utilizing ES6:

const largestOfFour = arr => arr.map(list => Math.max(...list))

Answer №3

The issue lies in the default sorting method which treats numbers as strings - causing "8..." to be greater than "1...".

One potential solution is to implement a custom comparison function:

function cmp(a,b){
  return a-b;
}

function getLargestNumbers(arr) {
  var i = 0;
  while (i != arr.length) {
    arr[i] = arr[i].sort(cmp).pop();
    i++;
  }
  return arr;
}

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

Expected Output: [ 8, 27, 39, 1001 ]

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

"PHP, AJAX, and JavaScript work together to run a loop that processes only the final element

Hello everyone, I need assistance in saving data from a loop. Here is the code snippet that I am working with: <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head> ...

Express Session Issue Preventing Ajax Call from Functioning

After testing the /temp route directly in the browser and then through an ajax call to the /test route, I noticed a difference in the session information. When accessed directly, the session retains the data added via the /temp route, but when called throu ...

difficulty receiving the information promptly via an AJAX request (utilizing AJAX and the 'for' loop)

Currently, I am successfully retrieving data from an ajax call for individuals. However, my next task is to retrieve multiple sets of data simultaneously. Here is the code snippet: for(var i = 1; i <= 2; i++){ console.log(i); $.ajax({ url: cal ...

Measuring the height of a div element using Vuejs

Let me explain my current situation: I am trying to determine the height of a DIV component in order to dynamically inform its child component about its size. I have been working on implementing manual loading mode, but I have encountered an issue where t ...

Implementing Jquery to Repurpose a Function Numerous Times Using a Single Dynamic Value

Important: I have provided a functional example of the page on my website, currently only functioning for the DayZ section. Check it out here Update: Below is the HTML code for the redditHeader click event <div class="redditHeader grey3"> & ...

Unable to export Interface in Typescript - the specific module does not offer an export named Settings

I am encountering an issue while trying to export/import an interface in Typescript. The error message I receive is causing confusion as I'm unsure of where I went wrong. Uncaught SyntaxError: The requested module '/src/types/settings.ts' ...

Experiencing a Node.js application issue with the error message "ERR

I'm encountering some serious challenges with a Node.js app that I am developing using Express, MongoDB, and Mongoose. Everything seemed to be functioning correctly last night when I used nodemon server.js to start the server. However, I'm now fa ...

Trouble Navigating the DOM

Can you assist me in choosing the correct option c? Below is the provided HTML code: <div id="a"> <div id="b"></div> <div id="app7019261521_the_coin_9996544" style="left: 176px; top: 448px;"> <a href="d.com" oncl ...

Transforming JSON format to another JSON format using AngularJS

I am in the process of setting up a questionnaire using angularjs. I have an array of responses that looks like the following, and I need to convert this object array into JSON format. How do I go about converting an object array into JSON format? ...

How to capture a change event in a dynamically loaded element using JQuery

I am facing an issue with dynamically added rows in my table. Each row contains a select option, and I need to trigger an action when the select is changed. However, since the rows are loaded after the page load, my function does not work as expected. < ...

Algorithm for searching and calculating with multiple words (Angular/Javascript)

As I work on loading a JSON file from the database containing two fields - words and grade, I face a challenge. Each word in the file is assigned a grade, for example, "true" has a grade of 1 while "lie" has a grade of -1. My goal is to take input from a t ...

Organizing an Ordered List of Items into Alternating Columns Using HTML

I am in the process of developing a responsive HTML design to showcase an array of organized data. For smaller screens, the layout will consist of a single column displaying items sequentially. However, on larger screens, the design should adapt to featur ...

jQuery and Ajax are facing a challenge in replacing HTML

Imagine a scenario where there is a button on a website that, when clicked, replaces a paragraph (<p>) with a header (<h1>). Unfortunately, the code to make this functionality work seems to be faulty: index.html <head> <script s ...

Issues with JQuery scroll() / scrollTop() functionality in Internet Explorer and Firefox

Our current script showcases a dotted line starting from the top of the screen leading to an up arrow. The position of the arrow changes based on how far the user has scrolled down the page, allowing them to click on the arrow and scroll back to the top. W ...

Utilize MetroUiCSS to effortlessly integrate a sleek calendar into your AngularJS application

I'm looking to incorporate a calendar from Metro Ui CSS into my project. Here is the link to the calendar: However, I am struggling with how to activate the calendar. I have already included all necessary scripts in my index.html (3 scripts) and have ...

Utilizing the power of jQuery within three.js

Thank you once again for your previous assistance, but I find myself in need of your expertise once more. I have successfully added markers to my map as desired. However, these markers now require functionality to be clickable. Specifically, when clicked, ...

Using Node.js to parse JSON data fetched from the web

My current challenge involves retrieving and parsing JSON from a web API (https://api.coinmarketcap.com/v1/ticker/?limit=3) in order to extract the name and price_usd fields. For example: [ { ... sample data provided ... } ] The code snippet I am wo ...

Developing custom functions in ejs for individual posts

In my blog, I have a feed where all users' posts are displayed dynamically using ejs. There is a comment section that remains hidden until the user clicks the comments button. Below is a snippet of my ejs file: <% posts.forEach(post => { %> ...

Clicking on the parent div with a Jquery onclick event does not trigger when the child image is clicked

I'm running into an issue with a simple code containing an image within a div Oddly enough, clicking on the div itself (even with padding) triggers the function, but clicking directly on the image does not. $(".parent0").click(function() { conso ...

Guide on accessing CGI Script response using AJAX

Greetings, Here is the situation: I'm working on a login form. Once the submit button is clicked, it needs to trigger a CGI script called "someurl?userName=user&password=pwd". Depending on the response from the script, I should be able to navigat ...