Arrange the array depending on the existence of properties in the objects

Is there a way to efficiently organize an array like the following in cases where certain fields are missing?

For instance, consider the current array:

const users = [
    {
        id: 1, firstname: 'Jerry'
    }, {
        id: 2, firstname: 'Thomas', lastname: 'Geib'
    }, {
        id: 3
    }, {
        id: 4, lastname: 'Berg'
    }, {
        id: 5, firstname: 'Ass', lastname: 'Noob'
    }, {
        id: 6, lastname: 'Jopa'
    }
]

The desired result should follow this order of sorting:

  1. An object containing both firstname and lastname
  2. An object with only firstname or lastname
  3. An object without either firstname or lastname

Resulting in the sorted array looking like this:

const users = [
    {
        id: 2, firstname: 'Thomas', lastname: 'Geib'
    }, {
        id: 5, firstname: 'Ass', lastname: 'Noob'
    }, {
        id: 1, firstname: 'Jerry'
    }, {
        id: 4, lastname: 'Berg'
    }, {
        id: 6, lastname: 'Jopa'
    }, {
        id: 3
    }
]

Attempts at sorting have been made, but the outcome is not as intended.

users.sort((a,b) => {
    if (a.firstname === b.firstname) {
        return 0
    }
    if (!a.firstname) {
        return 1
    }
    return -1
});

Answer №1

To organize the data, you can first check if a specific property exists and then sort the objects by their id in ascending order.

const users = [{ id: 1, firstname: 'Jerry' }, { id: 2, firstname: 'Thomas', lastname: 'Geib' }, { id: 3 }, { id: 4, lastname: 'Berg' }, { id: 5, firstname: 'Ass', lastname: 'Noob' }, { id: 6, lastname: 'Jopa' }];
    
users.sort((a, b) => 
    ('firstname' in b && 'lastname' in b ) - ('firstname' in a && 'lastname' in a) ||
    ('firstname' in b) - ('firstname' in a) ||
    ('lastname' in b) - ('lastname' in a) ||
    a.id - b.id
);

console.log(users);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To organize the items based on the number of properties they have, simply count the properties for each item and then sort them in descending order:

var animals = [
  {name: 'Lion', sound: 'Roar'}, 
  {name: 'Elephant', weight: 'Heavy', size: 'Large'}, 
  {name: 'Monkey'}, 
  {name: 'Tiger', color: 'Orange', stripes: true}, 
  {name: 'Giraffe', height: 'Tall', spots: true}, 
  {name: 'Zebra', stripes: true}
];
animals.sort(function(a, b) {
  var aw = ('sound' in a) + ('size' in a) + ('weight' in a);
  var bw = ('sound' in b) + ('size' in b) + ('weight' in b);
  return bw - aw;
});
console.log(animals);

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

An error occurred while attempting to reset your password on Parse.com (JS SDK) due to an

I am having trouble resetting my password in my angularjs App. I am utilizing Parse (js SDK) as the backend. Even though I am following the documentation and using Parse.User.requestPasswordReset, I keep encountering error 125 which states invalid email ad ...

Is the image overlay experiencing a flickering issue?

Last time, none of the solutions seemed to work quite right with the project, so let me try asking the question in a slightly different way this time. Basically, I have an image that, when someone hovers their mouse cursor over it, a div appears (containi ...

Working with structured data in Golang by accessing a variable within a struct that contains an array of other

func GetprofilesApi(c *gin.Context) { var p Profile profiles, err, count := p.GetProfiles() if err != nil { log.Fatalln(err) } c.JSON(http.StatusOK, gin.H{ "Number of Results": count, "profiles": profiles, }) } //Getprofiles() function func ...

Updating WordPress div content based on selected post type using dropdown menu

I am in the process of developing a WordPress plugin that will generate a custom post type and widget for users to add to their websites. The goal is to have the widget display a dropdown select box with titles of each post, and when a title is selected, t ...

Update the scrollspy navigation in a div with overflow by toggling the active class

Struggling to implement a navigation menu within a self-scrolling div using html/css/jquery. Looking for the menu items to toggle the active class when in view or at the top of the scrolling div. I'm essentially trying to achieve something like this ...

Find elements within an array that include a specific string

I've got several URLs listed below Reach out What's the best way to extract only "www.example.com" ? Can this be done easily with jsoup? I have both relative and absolute URLs and I only need to extract them without the tags. ...

Is there a way to refresh autocomplete/autofill after form submission with a custom JavaScript function?

I've developed a Vue application that includes a form. Once the user clicks on submit, an Ajax request is made using Axios through a JavaScript function. The data being sent is a custom JSON object that I have constructed by combining the information ...

The word "yargs" will not activate a command within a script

I have a NodeJs script that requires parsing command line arguments. Here is the code I have written: import yargs from "yargs"; import { hideBin } from 'yargs/helpers'; //.... yargs(hideBin(process.argv)).command('--add-item ...

Using jQuery to display items from GitHub API in a custom unordered list format

Attempting to access data from the GitHub API using jQuery (AJAX) and display it on a static webpage. Here are the HTML and JS code snippets: $(document).ready(function(){ $.ajax({ url: 'https://api.github.com/re ...

Which specific page initiates the post request?

Seeking help with my post request that originates from a specific page on my website: reqdata = 'text=' + mytext; $.ajax({ type: "POST", url: "/request.php", data: reqdata, cache: false, success: function(html) { alert(html) } ...

Challenges when utilizing the command "npm install" within a programmatic context

I'm really excited about the potential of using "npm programmatically," but I've hit a roadblock. The function "npm.load" doesn't seem to be triggering for me. None of the console logs inside of my "npm.load" or "npm.commands.install" functi ...

The TypeScriptLab.ts file is generating an error message at line 23, character 28, where it is expecting a comma

I am attempting to convert a ts file to a js file. My goal is to enter some numbers into a textarea, and then calculate the average of those numbers. However, I encountered an error: TypeScriptLab.ts(23,28): error TS1005: ',' expected. I have in ...

Guide on modifying values using both input fields and buttons at the same time

I am facing an issue with my input field that is designed to accept numbers. I want the value to be changed both via keyboard input and buttons. The buttons are functioning correctly unless I try to use keyboard input as well. For instance, if I enter 10 ...

How can I manually set a date in Angular bootstrap datepicker?

Using the Angularjs Bootstrap datepicker has been a great experience, but I encountered a problem when attempting to select the date using JavaScript. How can I ensure that the selected date in the datepicker matches the date read from a specific object, s ...

Tips for incorporating in/out animations with a container for the Slide feature:

I need help creating a component that will slide to the right when mounted, and to the left when unmounted. The Slide component should be contained in a div with the class "profile-slide-container", but I'm unsure how to achieve this. Below is the co ...

What is the most efficient way to transmit JSON data from a browser to a REST endpoint via Node.js, specifically in gzip format?

Currently working with node.js and express, I have a home page that hits my REST endpoint (PUT) after loading to send some JSON data. The data is not gziped when sending to the endpoint, but I want it to be in gzip form once it reaches the endpoint. Is thi ...

Steps for modifying material-ui timepicker to display time in a 24-hour format

Presently, I am utilizing a Timepicker from material-ui. It is currently configured with type="time", allowing me to select times throughout the day in 12-hour increments with an AM / PM choice. However, I wish to adjust my picker to a 24-hour format, elim ...

Using jQuery to deactivate the submit button when a field is empty or a checkbox is left unchecked

Today is my first attempt at using jQuery, and I could really use some assistance as I'm struggling to achieve the desired outcome. I'm dealing with a table of documents, each containing a checkbox for selection purposes. Additionally, there&apo ...

JavaScript utilized to create a fully immersive full-screen webpage

I have been trying to implement a code for creating a full-screen website that works on all browsers. Unfortunately, my current code only seems to be functioning properly on Mozilla browser. When I try to view the site in Chrome and make it full screen, it ...

Automating the process of running npm start on page load: A guide

Recently, I've been delving into learning npm in order to incorporate it into a website. I'm curious about how exactly it is used within a website - do you typically need to execute the command "npm start"? How does this integration work for a li ...