Sorting arrays with NaN values within objects will not result in a reordering when using the Array

I encountered a situation where I need to reorder items in an array based on the property minLVL of each object within the array.

However, I have discovered that this reordering only works if the previous and next items have the required minLVL field. If an object is missing the minLVL property, it remains in its original position instead of being moved to the bottom of the list.

How can I resolve this issue? Thank you

Example:

 var h = [
        {
            ID: 172
    },
        {
            ID: 179,
            minLVL: "30"
    },
        {
            ID: 169
    },
        {
            ID: 173
    },
        {
            ID: 167,
            minLVL: "25"
    },
        {
    ID: 175,
            minLVL: "10"
    }
    ]
    
          var n = h.sort((a, b) => Number(b.minLVL) - Number(a.minLVL))
    
    console.log(n)

Answer №1

If the value does not exist inside the sort function, you have the option to default those values to 0:

var arr = [{
  ID: 172
}, {
  ID: 179,
  minNumber: "30"
}, {
  ID: 169
}, {
  ID: 173
}, {
  ID: 167,
  minNumber: "25"
}, {
  ID: 175,
  minNumber: "10"
}]

var sortedArr = arr.sort((item1, item2) => (Number(item2.minNumber) || 0) - (Number(item1.minNumber) || 0))

console.log(sortedArr)

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: Jquery - function is not defined

Currently, I am developing a widget that is integrated into a client's website and it loads a jQuery file. However, we need to check if jQuery is already loaded on the client's page to prevent any conflicts, in which case we would not load our ow ...

The default zoom setting for ng-map is overly magnified when paired with the zoom-to-include-markers="true" feature

When using maps, I encountered an issue where having only one marker with the zoom-to-include-markers="true" attribute resulted in the map being overly zoomed in. Regardless of how I adjusted the zoom attribute, the result looked like this: https://i.sstat ...

Create a feature that allows users to view photos similar to the way it

I want to incorporate a Twitter feed on my website that displays images posted. Instead of having the images redirecting users to Twitter when clicked, I would like them to reveal themselves underneath when a link labeled "View Photo" is clicked, and then ...

I'm receiving an undefined output, does anyone have any suggestions to fix this?

let userInput = prompt("Please input a month number"); let monthName; switch(userInput) { case 1: monthName = "January"; break; case 4: monthName = "April"; break; case 8: m ...

Design an interactive vertical divider using d3

I am interested in developing a vertical rule similar to the one demonstrated at that updates its value dynamically based on the user's mouse movement. The example provided uses cubism.js, however, I would like to achieve the same functionality usin ...

What is the best way to execute 2 statements concurrently in Angular 7?

My goal is to add a key rating inside the listing object. However, I am facing an issue where the rating key is not displaying on the console. I suspect that it might be due to the asynchronous nature of the call. Can someone help me identify what mistak ...

Retrieving multiple images from a directory and storing the image filenames in a JSON array

Currently, I am attempting to locate and retrieve the images stored within a specific folder using the following code. This code successfully retrieves the image names along with the total count of images. Subsequently, my goal is to save this information ...

Creating unique parent-children category groupings in Excel VBA using collections and dictionaries - how can it be done?

Could someone assist me in understanding how to consolidate data by hierarchical groupings using VBA? PivotTables and tables are not feasible due to user constraints. The data includes three levels of groupings: Parent, Child, and Grain. Parents may have ...

Finding descendants using a jQuery object that has been saved

As I cycle through some unordered lists, I aim to retrieve all of the descendants using the saved jquery-wrapped selectors. Below is the HTML snippet: <ul> <li><a href="#">item 1</a></li> <li><a href="#"> ...

Can phantomJS be used to interact with elements in protractor by clicking on them?

While attempting to click a button using PhantomJS as my browser of choice, I encountered numerous errors. On my first try, simply clicking the button: var button = $('#protractorTest'); button.click(); This resulted in the error: Element is ...

Executing Javascript with Ajax requested data - A guide to making your script run smoothly

Battlefield Page In the graphic provided, there is a battlefield page featuring 20 users. To capture and store this data in a MySQL database, I have created a JavaScript script. However, an issue arises when trying to collect data from the next page after ...

Retrieving parameters from within iframe (child)

I currently have an embedded Iframe within a website, with both residing on different domains that I own. My goal is to pass a query parameter to the src attribute of the iframe. <iframe id="iframe" title="Survey" allowtr ...

How can I enhance a JavaScript Calendar with more features?

I recently acquired a JavaScript and jQuery calendar from CodeCanyon, which can be found here. I am now faced with the task of integrating this calendar into my workplace website. The current calendar on our ASPX-based site is limited to read-only functio ...

Even after being removed from the DOM using Ajax load, JQuery continues to execute

Currently, within my Laravel 5.2 single page application development, I am faced with the following issue. I have an add.blade.php file and an edit.blade.php file, both containing a script with the same class name and id. When I use .load to load add.blade ...

Is there a JavaScript toolkit specifically designed for animating mobile devices?

Currently in search of a JavaScript Library that is similar to impress.js, allowing me to create dynamic animations on text content that are compatible with iOS/Android. Although Hype by Tumult seems promising, I am not interested in an editor but rather ...

Ways to create distance between repeated cards in a loop. My method involves utilizing ajax, jquery, and bootstrap

view image description here What is the best way to create some space between these closely aligned cards? .done((todos) => { todos.forEach(el => { console.log(el) $("#todo-list").append(` <d ...

Questions about setting up a local development environment for Angular.js

After completing a few tutorials on Angular.js, I was eager to start building projects from scratch locally. However, despite my efforts, I have not been able to successfully set up my local development environment. I tried copying the package.json from A ...

Tips for sending the ampersand character (&) as a parameter in an AngularJS resource

I have an angular resource declared in the following manner: angular.module('xpto', ['ngResource']) .factory('XPTO', function ($resource, $location) { var XPTO = $resource($location.protocol() + '://' + $locatio ...

Experiencing difficulty with implementing an Angular filter to search through a list

Currently, I am utilizing an angular filter to search through a list. The searching functionality using the filter works as expected. However, I have encountered an issue with a checkbox labeled 'Select All'. When I search through the list and on ...

develop a customizable component library similar to shadcn for easy installation

Currently in the process of developing a design system, I am looking for advice on creating an installable library similar to shadcn. It is important to me that the source code of the components can be easily accessed and modified within my project. Is t ...