JS Array Sorting Failing to Function Properly

I have an array that looks like this: values = [250, 200, 300, 150, 300]

Here is the code I am using:


for (var i = 0; i < values.length - 1; i += 1) {
    if (values[i] > values[i + 1]) {
        var temp = values[i + 1];
        values[i + 1] = values[i];
        values[i] = temp;
    }
}

Unfortunately, this code is not producing the desired result. The current output is values = [200, 250, 150, 300, 300]

I am looking for a solution to achieve the correct sorting without relying on built-in functions.

Answer №1

Below is the code snippet you can use:

var numbers = [250, 200, 300, 150, 300];

for (var a = 0; a < numbers.length; a++) {
  var swapped = false
  for (var b = 0; b < numbers.length; b++) {
    if (numbers[b] > numbers[b + 1]) {
      temp = numbers[b + 1];
      numbers[b + 1] = numbers[b];
      numbers[b] = temp;
      swapped = true;
    }
  }
  if (!swapped) {
    break;
  }
}
console.log(numbers)

Answer №2

let numArray = [20, 35, 15, 10, 50, 65, 28,53, 42]
for (let i = 0; i < numArray.length; i++) {
   for (let j = 0; j < numArray.length; j++) {
      if (numArray[i] < numArray[j]) {
          let tempValue= numArray[j];
          numArray[j] = numArray[i];
          numArray[i] = tempValue;
      }
   }
}

console.log(numArray);

Answer №3

To effectively sort an array, it's important to utilize two nested loops.

nums = [250, 200, 300, 150, 300]
for (var i = 0; i < nums.length; i++)
  for (var j = i; j < nums.length - 1; j++) {
    if (nums[i] > nums[j]) {
      var temp = nums[j];
      nums[j] = nums[i];
      nums[i] = temp;
    }
  }

console.log(nums)

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

Error encountered when using the enter or return key with directive syntax

Newbie Alert I'm encountering something strange while attempting to create a custom directive in AngularJS. When I input this code: myModule.directive('myTab', function(){ console.log('--Inside TAB directive--'); return ...

Monitor Firebase information: trigger a function once the document object model has been refreshed

Currently, I am in the process of developing a real-time chat application using Vue.js and Firebase's real-time database. One specific functionality I am attempting to implement is ensuring that the chat window automatically scrolls to the bottom whe ...

Unable to successfully execute AJAX request using the POST method

Here we have a unique To-do app that functions by entering an item in the input field, storing it in an array of objects, and displaying the data using EJS. I attempted to use an AJAX request with XHR to interact with the URL, however, it appears to not b ...

Diagnosing circular JSON can be a challenging task

Encountering an issue in my error handler with the following message: Uncaught TypeError: Converting circular structure to JSON. I suspect that there might be an additional exception thrown within the JSON.stringify call leading to this error. It's p ...

Accessing an object's property within a mapped array in a Next.js application is possible

Currently, I am attempting to iterate through an array of objects and extract the link property as a <li></li> element. However, I am facing an issue where nothing is being returned: import { useState, useEffect } from "react"; import ...

What is preventing me from updating one dropdown list based on the selection made in another dropdown list?

I have a situation on a classic asp page where there are two dropdown lists: <select id="ddlState" name="ddlState" runat="server"> <option value="KY">Kentucky</option> <option value="IN" ...

Mastering the art of fetching data from a database for showcasing using a Chrome extension

Embarking on my first chrome extension development journey has been quite thrilling. The process involves an interesting workflow - once the extension is installed and activated, whenever a user hovers over a specific product/ID displayed on a webpage, the ...

Vue's watch function failing to trigger

Experiencing issues with Vue watch methods not triggering for certain objects even when using deep:true. Within my component, I am passed an array as a prop containing fields used to generate forms. These forms are dynamically bound to an object named cru ...

Utilizing JavaScript event handlers on dynamically appended elements after the document has finished loading

One issue I am facing is with a javasript function that needs to change the value of an element appended after the document has loaded. The problem arises when trying to intercept actions on a newly appended DIV, such as: <div class="new-div"></d ...

Using plain JavaScript (without any additional libraries like jQuery), you can eliminate a class from an element

I'm attempting to locate an element by its class name, and then remove the class from it. My goal is to achieve this using pure JavaScript, without relying on jQuery. Here is my current approach: <script> var changeController = function() { ...

When the mobile navigation bar is tapped, it remains open instead of closing

The persistent challenge of the mobile navbar failing to close upon clicking an item continues to baffle. Numerous attempts from Stack Overflow and even tweaks recommended by ChatGPT have been futile in resolving this issue. Despite trying alternative me ...

Styling a textbox within a gridview using JavaScript

Looking for a way to format a textbox within a gridview using JavaScript? Take a look at how the gridview columns are set up: <Columns> <asp:TemplateField> <ItemTemplate><asp:ImageButton runat="server" id="imgbtnEnterAmt" ...

The ripples can be found at the bottom of the map, not at the front

Having an issue when working with Globe where Ripple rings are always appearing on the backside of the map, rather than in front of it Referencing the source code from https://github.com/vasturiano/globe.gl/blob/master/example/random-rings/index.html and ...

Challenge with setting asynchronous default value in React Material UI Autocomplete

Utilizing the 'Material UI' Autocomplete component to show a dropdown in my form. Whenever the user wishes to edit an item, the dropdown should autofill with the corresponding value fetched from the database. Attempting to simulate this scenario ...

Creating a dynamic menu item in React using the useState hook

I have encountered an issue when trying to create a menu with active styling using useState in React JS. The problem is that the menu item stays active even after clicking on another item, instead of reverting back to its inactive state. Surprisingly, this ...

Render multiple checkboxes with values from an array of objects passed as a prop to a child component using a v

I am facing an issue with my Vue components 'Parent' and 'Child'. Each child component has a checkbox with a :checked prop. In the Parent component, I iterate through an array of objects and pass props to the child. Although I can emit ...

Exploring the bind() method in the latest version of jQuery,

After upgrading my JQuery version, one of the plugins I was using stopped working. Despite trying to use the migrate plugin and changing all instances of bind() to on(), I still couldn't get it to work properly. The plugin in question is jQuery Paral ...

Transfer information to an ExpressJS server in order to display a fresh view

I'm struggling to figure out how to transfer data from the client side to an ExpressJS server in order to generate a view based on that information. When users choose different parameters on the client side, they update the 'data-preference&apos ...

Issue with parent-child communication in React.js causing malfunction

I am facing an issue with maintaining state between two different JavaScript files using React. The parent class, break.js, is defined as follows: export default function AlertDialog(props) { const [demoOpen, setDemoOpen] = React.useState(true); ...

Using jQuery to create a fade in/fade out effect within a list of items

I'm currently experimenting with jQuery's fadeIn/fadeOut effects on images used as buttons within an unordered list. My goal is to have the hovered image fade in quickly and out slowly upon mouseout. The issue I'm encountering is related to ...