evaluating an object against null

When comparing two objects a and b, it is necessary to ensure that one of them is not null.

However, deciphering this can be quite chaotic.

{}    - null   => -0
[]    - null   => 0
1     - null   => 1
"1"   - null   => 1
true  - null   => 1
false - null   => 0
"a"   - null   => NaN
null  - null   => 0

"a" == null    false
"a"  > null    false
"a"  < null    false

let arr = [
  { name: "a" },
  { name: null },
  null,
  { name: "zaa" },
  { name: "dgh" }
];
let sortByName = function (a, b) {
  if (a == null || b == null) return a - b;
  if (a.name == null || b.name == null) return a.name - b.name;
  return a.name.localeCompare(b.name);
};

console.log(arr.sort(sortByName));

The resulting order is as follows:

0: {name: 'a'}
1: {name: null}
2: null
3: {name: 'dgh'}
4: {name: 'zaa'}

Can you provide an explanation for this outcome?

Answer №1

null - {} === NaN
{} - null === -0

Here:

if (a == null || b == null) return a - b;

You are subtracting anything from null or null from anything, if one of the 2 values is null.

Replace null with an empty space and use that in your comparison:

let data = [
  { title: "apple" },
  { title: null },
  null,
  { title: "banana" },
  { title: "carrot" }
];
let sortByTitle = function (item1, item2) {
  return (item1?.title ?? '').localeCompare(item2?.title ?? '');
};

console.log(data.sort(sortByTitle));

Answer №2

To ensure that null is placed before {name: null}, you can enhance the solution provided by @Cerbrus.

An easy approach is to transform both terms a and b into values that will ultimately sort as desired. One simple method is to add a specific character in front of the input terms for sorting purposes.

For example:

If the term is null, return `0`;
If the term is `{name:null}`, return `1`;
For everything else, return `3` + the term;

This technique is similar to creating a compound index.

By implementing the above logic, it becomes straightforward to customize the sorting based on specific conditions. For instance, if you wish to move null to the end like undefined, simply adjust its prefix, such as changing it to 4.

For implementation:

let arr = [
  { name: "a" },
  { name: null },
  null,
  { name: "zaa" },
  { name: "dgh" }
];

function toStr(a) {
  if (a === null) return '0';
  else if (a.name === null) return '1';
  else return '3' + a.name;
}

let sortByName = function (a, b) {
  return toStr(a).localeCompare(toStr(b));
};

console.log(arr.sort(sortByName));

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

How can one utilize a second drop-down list in asp.net to alter the selected index and visibility of a drop-down list?

I am working on an asp.net application that includes a drop down list with the following structure: <asp:DropDownList runat="server" ID="ddlChanges" CssClass="selectstyle" onchange="javascript:ddlChangesChanged();"> <asp:ListItem Text="-- Select ...

Showing text on an ajax loader

While making an ajax call, I have implemented functions that are called on success. To enhance user experience, I am displaying a spinner during the call and hiding it once completed. My goal is to show a message along with the spinner to indicate which fu ...

How can I prevent users from inputting negative numbers in a cellEditable material-table?

In my project, I am utilizing a material table with editable cells. I need to implement a restriction that prevents users from entering negative numbers in the field and displays an error validation message. How can I achieve this functionality? Check out ...

Utilizing next/image as a backgroundImage in a div container

Currently, I am working with nextjs and I am trying to set a background Image for a specific div using next/image. Most of the sources I found only explain how to implement full screen background images with next/image, not for a single div. I stumbled upo ...

Detecting when the "enter" key is pressed using Jquery instead of relying on a mouse click

One issue I am facing is that jQuery is detecting the "enter" key press instead of mouse clicking on the submit button when trying to submit a form. The submit button works fine on the first attempt, but after that it only responds to the "enter" key. He ...

The jQuery autocomplete feature with typeahead suggestions fails to appear following a successful AJAX request

I am currently using typeahead.js to incorporate tags into my multiple input setup. The tagging function works as expected, however, I am facing an issue where the autocomplete suggestions are not appearing. Is there a solution to fix this problem? Despit ...

"Encountering a strpos() issue while working with the Simple HTML DOM

Efficient HTML Parsing Comparison (1 min, 39s) <?php include('simple_html_dom.php'); $i = 0; $times_to_run = 100; set_time_limit(0); while ($i++ < $times_to_run) { // Find target image $url = "http://s ...

Transmitting a variable string from JavaScript to PHP through AJAX

How can I pass a variable value from an HTML page using JavaScript to PHP? In my index.php file, I have the following code: $amount = $_GET['pricenumb']; echo $amount; Here is the JavaScript code I used to call on click of a button and send th ...

Guide to extracting a key from the route module with the help of vuex-router-sync

I have a Vuex store setup as shown below, and I am using vuex-router-sync to keep it in sync. This plugin adds a router module to my store. However, I am unsure of how to retrieve this object from the store since there are no associated getters with this m ...

Changing the background color of MUI TextField for autocomplete suggestions

I am currently facing an issue with the background color of auto-complete fields in my React.js and Material UI app. The auto-complete fields are adding a white background which is unnecessary. Interestingly, when I manually add text, this issue does not ...

Is axios allowed to be used in this scenario?

As a newcomer to web development, I apologize in advance if my question seems basic or if the details provided are insufficient. Nevertheless, I hope you can assist me with the following query: Is it possible to execute an axios.post request within a vue. ...

Waves emanating from the heart of rings

I'm experimenting with creating a ripple effect using Anime.js on an array of dots forming circles. Despite trying various methods, I can't seem to achieve the desired result. Does anyone have any suggestions on how I can make it work? Here&apos ...

I encountered an issue while trying to integrate react-alert into my React application. An Uncaught Error was thrown, stating that objects are not valid as a React

I encountered the following error: react-dom.development.js:14748 Uncaught Error: Objects are not valid as a React child (found: object with keys {$$typeof, render}). If you meant to render a collection of children, use an array instead. in Unknown (c ...

Placing buttons on top of a video within a div container

I am facing a challenge with implementing custom controls on a video embedded in my webpage. I have tried setting a div to absolute position for the buttons, but they are not clickable. Is there a way to achieve this without using jQuery? I need the butto ...

What is the best way to merge different Vue JS instances (each linked to different html divs) into one cohesive unit using Vue

Essentially, I have a scenario where I've created two HTML divs named vueapp1 and vueapp2. Both of these divs serve the same purpose of displaying information and are linked to their individual Vue instances for extracting JSON data and presenting it. ...

React not functioning properly when packaged with Webpack

I tried implementing React in the simplest way possible, but I am facing some issues. After bundling React and opening the index.html page, it shows up completely blank with no console errors to indicate any mistakes. Below is my webpack.config.js: const ...

After clicking the create button in AngularJS, the ngModel values become empty

My form has been simplified by using ngRepeat to create the input fields. The attributes for each item are defined in my controller. Below is the code for the ModalCtrl: ... $scope.form = [ { label: 'First Name', fieldType: 't ...

How can you efficiently pass multiple JSON files as arguments for Observable Arrays, especially when the values from one file are required for use in another file?

My goal is to utilize $.getJSON to retrieve data from two JSON files and assign their values to observableArrays. Currently, I have hard-coded the JSON data into the observableArray. You can view an example on this JSFiddle link. This was my initial appro ...

Creating a tree structure in Node.js using JSON data while preventing duplicates: A step-by-step guide

My MongoDB has some JSON data that looks like this: [ { "_id": { "$oid": "1" }, "name": "A Inc", "children": [ {"$oid": "2"},{"$oid": & ...

Retrieve request body/header variables in JWT strategy using Nest JS

Is there a way to retrieve the header variables or request body in a strategy? The JWT structure within the JwtStrategy currently appears as follows: @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor( private re ...