Exploring the method of finding the second lowest and second highest values within an array

Hey there fellow Stack users,

Please excuse me if this question has already been asked or is too basic (I'm still new to Javascript).

Recently, I've been working on some w3c js challenges: Create a JavaScript function that can identify the second lowest and second greatest numbers in an array of stored numbers.

Here's my attempt:

var numbers = [3,8,5,6,5,7,1,9];
var outputArray = [];

function extractNumbers() {
  var sortedNumbers = numbers.sort();
  outputArray.push(sortedNumbers[1], numbers[numbers.length-2]);
  return outputArray;
}

extractNumbers();

Now, here's the solution they provided:

function Second_Greatest_Lowest(arr) {  
  arr.sort(function(x,y) {  
    return x-y;
  });  

  var unique = [arr[0]];  
  var result = [];  

  for(var j=1; j < arr.length; j++) {  
    if(arr[j-1] !== arr[j]) {
      unique.push(arr[j]);  
    }  
  }

  result.push(unique[1], unique[unique.length-2]);
  return result.join(',');  

}  

alert(Second_Greatest_Lowest([1,2,3,4,5])); 

I understand that the loop goes through until the input length, but I'm confused about the nested if statement inside the loop. It seems like a longer route to the solution.

Thanks!

Answer №1

Your answer is not accurate when dealing with inputs like [3,8,5,6,5,7,1,1,9]. Your suggested method incorrectly identifies the second lowest number as 1 instead of 3.

The approach recommended by the platform considers this issue by including an if statement within the loop to ensure that each number is only counted once. This guarantees that the second element in the sorted array will indeed be the second lowest number.

It may seem like a convoluted solution at first glance.

You opted for a shortcut, which unfortunately does not handle all potential scenarios accurately ;-)

Answer №2

Examining the loop at hand:

for(var x=0; x < uniqueArr.length; x++) {  
    if(uniqueArr[x] !== uniqueArr[x - 1]) {
      newArr.push(uniqueArr[x]);  
    }  
  }

The use of the variable name newArr hints at its purpose - creating a new array with only unique elements. By comparing each element to its predecessor, we ensure that only distinct values are added to the new array.

Following this logic will lead you to the same outcome as your implementation.

Answer №3

import java.util.Arrays;

public class BubbleSortWithMinMax
{
    public static void main(String[] args)
    {

        int temporary;
        int[] array = new int[5];
        array[0] = 3;
        array[1] = 99;
        array[2] = 55;
        array[3] = 2;
        array[4] = 1;

        System.out.println("Original array: " + Arrays.toString(array));
        
        for (int i = 0; i < array.length; i++)
        {
            System.out.print(array[i] + " ");
        }

        for (int i = 0; i < array.length; i++)
        {
            for (int j = 1; j < array.length - i; j++)
            {
                if (array[j - 1] > array[j])
                {
                    temporary = array[j - 1];
                    array[j - 1] = array[j];
                    array[j] = temporary;
                }
            }
        }

        System.out.println("\nSecond Minimum and Second Maximum:");
        for (int i = 0; i < 1; i++)
        {
            System.out.println(array[i+1]);
        }
        
        for (int i = 0; i < 1; i++)
        {
            int a = array.length - 2;
            System.out.println(array[a]);
        }

    }
}

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

Can you compare the two input values for validation in an HTML and JavaScript form?

I need assistance with comparing two input values, minN and maxN. I want to display an alert if the logic between these two values is not met. Below is the code snippet that I am using: HTML: <table> <tr> <th>Minimum N</t ...

DataTables.Net Buttons not appearing in the interface

I have a basic MVC project that utilizes BootStrap4 and dataTables.Net. When the page loads, an Ajax call is made to fetch data for a table. However, despite following the documentation, I'm unable to get the buttons to display on the page. Everything ...

Cannot display data in template

After successfully retrieving JSON data, I am facing trouble displaying the value in my template. It seems that something went wrong with the way I am trying to output it compared to others. My function looks like this, getUserInfo() { var service ...

Errors with displaying prototype function in AngularJS ng-repeat as undefined

Encountering a problem where a function is returning 'undefined' in a select field. <select name="supervisor" ng-model="editJudge.superID" ng-options="supervisor.legalProID as supervisor.fullName for supervisor in supervisors" cla ...

A guide on importing JSON files and rendering them in three.js

Greetings fellow developers! I have written some code to import a JSON file and render it using three.js. The JSON file was exported from the three.js editor. Strangely, there are no errors appearing in the console. window.onload = function() ...

Exploring JSON API Data with Vue Js

While working on my Vue Js project, I encountered an issue with displaying data from an API in JSON format. Despite using this.obj =JSON.stringify(this.Flats); and successfully seeing all the data using console.log, I struggled to loop over and view the pa ...

Numerous data points within PHP form/query

Before diving in, I want to mention that I have already tried searching for a solution, but none of the other questions were helpful in my case. I came across a code that seems to be perfect for my needs (here), but I am facing an issue when trying to fet ...

The curious behavior of $viewContentLoaded in Angular

For my jQuery code, I wanted it to run immediately after the template view was loaded and the DOM was modified. To achieve this, I initially used the $viewContentLoaded event in my controller. $scope.$on('$viewContentLoaded', function(){ // ...

Discover all undefined variables in the project using Node.js

Currently working on developing a backend API using Node.js Encountering issues at times where unit tests fail and error message 'data is not defined' appears Fortunately, TypeScript has proven beneficial in resolving such problems with its l ...

Is there a reason why I can't load all Google charts on one webpage?

I am trying to use the Google Charts API to display various charts on my web page. However, I seem to be encountering an issue where the last chart is not loading correctly. Can someone point out what I might be missing in my code? I would greatly apprecia ...

Does the presence of XHR calls with application/json as the 'type' indicate that the application is using AJAX technology?

Forgive my lack of knowledge on this topic as I am still in the process of learning. I am exploring the possibility of implementing a solution on my website where I can embed a JavaScript code that will make API calls to display images. I am curious to kno ...

An error occurred: TypeError - Attempting to access a property that is undefined, even

I am struggling to implement default values when deleting a list from my todo list application. I want the current list info to temporarily use default values until the post request refreshes the available lists. Despite trying various methods to set defau ...

Prevent the execution of an event while another event is already running in jQuery

Two events are in play here: one with the onclick function which scrolls to a specific div upon menu item click, and the other utilizes the onscroll function to "highlight" the corresponding menu item when scrolling near the div. The burning question is: ...

The hyperlink in the HTML code is malfunctioning

While working on a Wix website, I encountered an issue with the code snippet below: // JavaScript var countries = [ { name: 'Thailand', link: 'www.google.com' }, { name: 'Tanzania', link: '' }, { name: &ap ...

Clicking outside the div will cause the div to be hidden

Looking for some help with a jQuery issue. I have a pop-up that opens when a div is clicked, but I want it to close when clicking outside of the div instead of just on the close button. <a class="close-up" href="#" onclick="popup('popUpDiv')" ...

Unclear when notifying div content

After creating a PHP page, I encountered an issue while trying to select the inner text of a div and alert it with jQuery. Instead of getting the expected result, it keeps alerting "undefined." What could possibly be causing this? Here is the code snippet ...

What is the process for retrieving randomized data using mongoose?

I recently came across the mongoose-random package which allows for retrieving a JSON array of random records using mongoose. My goal is to retrieve three random records with a specific field. Despite reviewing the documentation, I have yet to find a work ...

Angular 6 and Typescript: How to Map Objects in Arrays within Arrays

We currently have two arrays named speisekarte (consisting of 10 objects) and essensplan (containing 8 objects). const speisekarte = [ { id: 11, name: 'Kabeljaufilet', price: 3.55, type: 'with fish' }, { id: 12, name: 'Spaghet ...

Angular ngFor not displaying the list

I'm encountering an issue with my HTML page where I'm using NGFor with an array. The error message I receive is as follows: landingpage.component.html:142 ERROR Error: Cannot find a differ supporting object '[object Object]' of type &ap ...

Is it possible for object destructuring in Javascript to include dynamic non-rest keys using ...rest?

Suppose we have an object: const obj = { key1: "value1", key2: "value2", key3: "value3", key4: "value4" }; My goal is to filter out specific keys from this object to create a smaller one. I am aware of the following ...