Reorder an array of objects in JavaScript alphabetically, taking into account any possible null values

Encountering a problem with sorting contacts by first name, especially when some contacts are missing this information. Any suggestions on how to modify the method for such cases? Thanks!

This is the current sorting function I am using:

function sortAZ(ob1,ob2) {
    var n1 = ob1.firstName.toLowerCase()
    var n2 = ob2.firstName.toLowerCase()
    if (n1 > n2) {return 1}
    else if (n1 < n2){return -1}
    else { return 0}//nothing to split
};

data.sort(sortAZ);

Answer №1

function customSort(obj1, obj2) {
    // Handles case they're both equal (or both missing)
    if (obj1 == obj2) {return 0}
    // Handle case one is missing
    if (obj2 == null|| obj2 == "") {return 1}
    if (obj1 == null|| obj1 == "") {return -1}

    var name1 = obj1.firstName.toLowerCase()
    var name2 = obj2.firstName.toLowerCase()
    if (name1 > name2) {return 1}
    else if (name1 < name2){return -1}
    else { return 0}//nothing to split
};

Answer №2

The approach you take will vary depending on how you wish to handle objects lacking the specified attribute.

To ensure the sort function does not compare non-existent attributes, one can include the following check at the beginning:

if (ob1.firstName === undefined || ob2.firstName === undefined) {
    return 0;
}

Answer №3

Special thanks to PherricOxide for inspiring this tweaked response.

function alphabetize(obj1, obj2) {
    // Check if they are the same or missing
    if (obj1 == obj2) {return 0}

    // Handle cases where firstName is missing
    if (!obj2.firstName || obj2.firstName === "") {return 1}
    if (!obj1.firstName || obj1.firstName === "") {return -1}

    var n1 = obj1.firstName.toLowerCase();
    var n2 = obj2.firstName.toLowerCase();
    if (n1 > n2) {return 1}
    else if (n1 < n2) {return -1}
    else { return 0}//no distinction needed
};

Answer №4

Make sure to check for the presence of the objects and their properties before comparing them. If they are missing, return 1 or -1 to properly sort them at the end or on top.

function sortAZ(ob1, ob2) {
    if (!ob1) return -1;
    if (!ob2) return 1;
    // if (ob1 == ob2) return 0; // equal
    if (typeof ob1.firstName != "string") return -1;
    if (typeof ob2.firstName != "string") return -1;

    var n1 = ob1.firstName.toLowerCase()
    var n2 = ob2.firstName.toLowerCase()
    if (n1 > n2) return 1;
    if (n1 < n2) return -1;
    return 0; // equal
}

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

Is there a way to automatically hide a div based on a checkbox value when the page loads?

How can I hide a div in my view when a checkbox is not checked upon page load? <input type="checkbox" class="k-checkbox" id="chkInvoiceStatusActive" asp-for="InvoiceStatus" value="true" /> <input t ...

Ways to precisely define a matrix of type Integer[][] in a coding scenario

It's an easy question for someone skilled in this. Create a two-dimensional array named 'res' with some hard-coded values like the following: Integer[][] res = new Integer[][] {.....hard code some values here on 2 dim...} How can you modif ...

Discovering ways to fetch an array of objects using object and arrays in JavaScript

When comparing an array of objects with a single object and listing the arrays in JavaScript, specific conditions need to be met to retrieve the array of objects: If the itemvalue and idvalue are the same, check if the arrobj cid has the same codevalue ...

Issue with dynamic creation of menu in React Material UI where onClose function is unable to reference a variable inside the function

As I develop an app, I have chosen to dynamically construct the settings menu based on a JSON file. { categories: [ { name: "General", index: 1, items: [{ name: "Dark Mode", index: 1 ...

React-Select for Creating a Dynamic Multi-Category Dropdown Menu

I am looking to incorporate react-select into my project for a multi-category dropdown list. Specifically, I need the ability to select only one option at most from each category. To better illustrate this requirement, consider the following example wher ...

Utilize a while loop in JavaScript to trigger a message when a variable dips below zero

Forgive me if I seem clueless. I am a beginner in the world of Javascript and am currently experimenting with loops. At the moment, I am toying around with this particular piece of code: <!DOCTYPE html> <html> <body> <button oncl ...

Using jquery, transform json data into html table format

As a beginner in the realm of coding, I am currently experimenting with extracting data from my json file and transforming it into an HTML table. My tool of choice is the Atom code editor, and I am attempting to use JavaScript, specifically jQuery, to it ...

What is the best way to compare an array with comma-separated values in JavaScript?

I have a scenario where I have two arrays, one for categories and the other for products. Each product contains multiple categories as a comma-separated string. My goal is to match a specific category with each product's product_category value and the ...

The module specifier "tslib" could not be resolved due to a TypeError. It is necessary for relative references to begin with either "/", "./", or "../"

Hey there, I recently started learning npm. I'm trying to install "@fullcalendar" and use it, but I keep getting this error message: "Uncaught TypeError: Failed to resolve module specifier "tslib". Relative references must start with either "/", "./", ...

Ways to retrieve the file name and additional attributes from a hidden input type

Is it possible to access the file name and other attributes of a hidden file when submitting it using the <input type="hidden"> tag? My current project involves drag and drop file functionality on a server using Node.js. If I am able to dynamically ...

Leveraging packages obtained from npm repositories

Recently, I came across this guide about React that included a paragraph that left me puzzled. According to the guide, CommonJS modules (found in npm) cannot be directly used in web browsers due to technical limitations. Instead, you need a JavaScript " ...

Transforming the exterior designs in Angular

I am in the process of transitioning a product management admin site to Angular. Currently, all my views (such as the product list, detail view, and edit) are displayed inside an ng-view on my admin page, which is working well. However, I have a link for e ...

Determine in C++ whether a given input string matches the array string in a class

I'm currently facing an issue with searching for a book in my array using either the title or ISBN. Despite implementing a search function, it fails to find books that are already in the array. The code seems correct to me, but I can't figure out ...

PHP: A guide to traversing a multi-dimensional array and printing out the arrays within it rather than the individual elements within those arrays

Usually when I search, I find what I need, but this time I'm a bit lost. I decided to create a multidimensional array using the following approach: Below is the code - from input to push: This is the text entered into the textarea: VIE-CAI HA ...

Apply an opacity setting of 0.5 to the specific segment representing 30% of the scrollable div

I have a scrollable container for displaying messages. I would like to apply an opacity of 0.5 to the content in the top 30% of the container, as shown in this image: https://i.stack.imgur.com/NHlBN.png. However, when I tried using a background div with a ...

The REST request is preventing the JavaScript on the page from executing

Utilizing REST to POST data through Firefox's Poster tool and encountering a url: http://[ip]/page.jsp?paramater1=whatever&parameter2=whatever (Content Type: application/x-www-form-urlencoded) The page.jsp includes: <body onload="onload()"&g ...

Is there a way to use an Angular $watch to determine the specific changes made to $scope.value?

I am monitoring a variable called $scope.value with a watch in my code. There are two ways in which the value can be updated: The first is by updating it from the controller, such as through any services. The second way is that any input event can also ...

"User-friendly Material-UI input field paired with a clear label

Seeking guidance on creating a text field with a label using the material-ui library. I am searching for something similar to this example: https://github.com/callemall/material-ui/blob/master/src/TextField/TextFieldLabel.jsx Unfortunately, I have been ...

Issue with AngularJS UI Router not loading the inline template and controller

I am trying out UI Router for the first time in my AngularJS project. I am facing an issue where, when I click on a link to view a post, it doesn't display. The post template is not visible and I remain on the home page. The URL flashes as http://loc ...

Is it possible to import files in Vue JavaScript?

I want to incorporate mathematical symbols from strings extracted from a JSON file. While it seems to work perfectly on this example, unfortunately, I encountered an issue when trying it on my own machine. The error message 'Uncaught (in promise) Refe ...