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

Encountering a 403 Forbidden error while attempting to access a website built with Next.js

Every time I try to access the Next.JS website that's been deployed on IIS using the HTTP address, I'm faced with this error message: Get http://...../_next/static/chunks/webpack-73760e2208a549db.js net:: ERR_ABORTED 403 (Forbidden) However, w ...

Posting a string using AJAX to the Java backend through JavaScript

I'm currently working on a comment section for a Web Client. There are two tables involved - one for the comments and another for the users. My goal is to send input data from HTML <input> tags to a Java Service where the data will be processed ...

The issue with dynamic sizing in React and Tailwind is that it does not consistently work with arbitrary sizes. Some sizes do not appear properly, causing items to

In this code snippet, I am attempting to create a circle component of dynamically sized using html div and Tailwind CSS w-[diameter] & h-[diameter] attributes in a create-next-app@latest project. However, the circle fails to render properly with certa ...

Unsuccessful translation of HTML symbol codes within a toggle function using jQuery

Is there a way to toggle between the symbols + and - using HTML entity codes &#43; and &#45;? I have attempted different solutions for toggling HTML content, but none seem to work correctly with these specific codes. It toggles once, but doesn&apo ...

Having a problem with the glitch effect in Javascript - the text is oversized. Any tips on how to resize

I found some interesting code on the internet that creates a glitch text effect. However, when I implement it, the text appears too large for my webpage. I'm struggling to adjust the size. Here is the current display of the text: too big This is how ...

What are the ways to change a PDF file or web address into a DOCX document using NodeJS?

I've been doing some research on converting URLs to DOCx or PDF to DOCx in NodeJS, but I haven't found a proper solution yet. I tried reaching out to PhantomJS, but it only converts URLs to PDF. Do you have any idea if PhantomJS can convert to D ...

How do I incorporate a standalone checkbox in a React Material-UI table without affecting row selection upon clicking?

I would like to have a distinction between clicking on a checkbox and clicking on a row. Specifically, I want the following behavior: when I click on the checkbox, only the checkbox should be checked; and when I click on the row, only the row should be se ...

Tips for retrieving a value from fs.accessAsync function

I am currently working on verifying the accessibility of a specific file, folder, or directory for reading purposes. I have implemented the code below, which functions properly. However, there are a couple of aspects that I would like to inquire about: 1. ...

Exploring an Array Based on User's Input with JavaScript

Looking to implement a search functionality for an array using AJAX. The array is pre-populated with values, and the user will input a value in a HTML text box. If the entered value is found in the array, it should display "Value found", otherwise "not f ...

What is the best way to loop through a group of WebElements, and only log the results that contain a specific substring?

In my test case, I'm utilizing Mocha to handle the scenario. The test appears to be passing successfully, however, no logs are being printed... it('Is 'Mooooooo!!!! I2MaC0W' a Substring in Results?', function() { this.timeout(50 ...

Dealing with Regular Expressions in Javascript and PHP Challenge

I am struggling to achieve the same outcome with my JavaScript as I do with my PHP code. The issue lies in how JavaScript omits backslashes, unlike PHP. To address this, I have included random forward and backward slashes to cater for different systems. Se ...

Load the dropdown menu in the select element using the AngularJS $ngresource promise

I have a select box on my webpage that I need to fill with data received from a server. I am currently using a service to fetch this data, but I'm unsure how to access the values returned from the promise and populate the ng-options in the select tag. ...

Exploring Firefox webpage data with JavaScript or browser extensions

Have you ever wondered if it's possible to retrieve the "Modified" information seen in Firefox when selecting "View page Info" by just using a JavaScript extension? ...

Using Google App Script to transfer specific columns of a row to a different tab based on the value in a particular column

I have a script that moves rows based on a specific value in a column, but I am looking to only transfer certain columns within those rows. This is the current script I am using: //Script to move rows from Form tab to Des tab function moveSafeRows() { v ...

effective ways to extract objects from nested structures using a specific identifier

In this sample data, I am looking to filter an object based on its ID key let myData = { "nodeInfo": { "9": { "1": { "ID": "14835" ...

Filtering without the includes() Method

I have two Objects that are structured as follows: export const recipes: Recipe[] = [ new Recipe( id: "Green", scenario: ["1", "2"]), new Recipe( id: "Blue", scenario: ["1", "2","2"]) ]; export const scenarios: Scenario[] = [ new Scenario( id: "1 ...

Do not fetch data again after a re-render

My code is facing an issue where every time I click toggle, the Child component re-renders and triggers another API request. My goal is to fetch the data once and then keep using it even after subsequent re-renders. Check out the CodeSandbox here! functio ...

Tips for accessing jQuery UI tab elements and adjusting visibility for specific panels

How can I retrieve the panel numbers of jQuery UI tabs and adjust their visibility using CSS? I am looking to identify the panel numbers of each tab and control the visibility of certain tabs. <div id="tabs"> <ul> <li><a href="#"> ...

Vuejs tutorial: Toggle a collapsible menu based on the active tab status

I am using two methods called forceOpenSettings() and forceCloseSettings() to control the opening and closing of a collapsible section. These methods function properly when tested individually. However, I need them to be triggered based on a specific condi ...

Obtain the accurate sequence of tr elements in the form of a jQuery object

Even though you can define tfoot before tbody in the source code, when displayed in the browser tfoot will still appear last: <table> <thead><tr><th>i get displayed first</th></tr></thead> <tfoot><t ...