Tips for organizing an array of objects that contain null properties

Here is an array that I need help with:

"data": {
    "risks": [
      {
        "id": "22",
        "name": true,
        "surname": 0.5,
        "age": 0.75,
        "heigth": 50,
        "num1": [],
        "num2": []
      },
      {
      "id": "55",
        "name": true,
        "surname": 0.5,
        "age": 0.75,
        "heigth": 50,
        "num1": [],
        "num2": []
      },
      {
          "id": "33",
        "name": true,
        "surname": 0.5,
        "age": 0.75,
        "heigth": 50,
        "num1": [1,2,3,4,5],
        "num2": [4,5,6,9]
      }
]}

I'm looking to sort the array in a way that objects with either empty num1 or num2 are placed at the end of the array. I attempted to do this using the code below, but it didn't achieve the desired result.

array.sort((x, y) => !!y.num1.length ==0- !!x.num1.length ==0|| !!y.num2.length ==0- !!x.num2.length ==0);

Answer №1

Ensure to provide an integer as the return value from your custom sort() function. It should be either 0, > 0, or < 0 based on the comparison result.

A straightforward method to validate if either num1 or num2 in any object contains a value is by adding their lengths together and comparing them, like this:

const obj = {data:{risks:[{id:"22",name:!0,surname:.5,age:.75,height:50,num1:[],num2:[]},{id:"55",name:!0,surname:.5,age:.75,height:50,num1:[],num2:[]},{id:"33",name:!0,surname:.5,age:.75,height:50,num1:[1,2,3,4,5],num2:[4,5,6,9]}]}};

obj.data.risks = obj.data.risks.sort((a, b) => (b.num1.length + b.num2.length) - (a.num1.length + a.num2.length));
console.log(obj.data.risks);

Keep in mind that this method assumes the arrays in the objects are always empty and not null.

Answer №2

One suggestion is to sort empty arrays by taking the delta of the negated length and moving them to the bottom.

const
    data = [{ id: "22", name: true, surname: 0.5, age: 0.75, heigth: 50, num1: [], num2: [] }, { id: "55", name: true, surname: 0.5, age: 0.75, heigth: 50, num1: [], num2: [] }, { id: "33", name: true, surname: 0.5, age: 0.75, heigth: 50, num1: [1, 2, 3, 4, 5], num2: [4, 5, 6, 9] }, { id: "33", name: true, surname: 0.5, age: 0.75, heigth: 50, num1: [], num2: [4, 5, 6, 9] }, { id: "33", name: true, surname: 0.5, age: 0.75, heigth: 50, num1: [], num2: [4, 5, 6, 9] }];
    
data.sort((a, b) =>
    !a.num1.length - !b.num1.length ||
    !a.num2.length - !b.num2.length
);
    
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

ExitDecorator in TypeScript

Introduction: In my current setup, I have an object called `Item` that consists of an array of `Group(s)`, with each group containing an array of `User(s)`. The `Item` object exposes various APIs such as `addUser`, `removeUser`, `addGroup`, `removeGroup`, ...

Dynamic Weight feature in Prestashop allows for automatically adjusting shipping costs

I'm curious about displaying the dynamic weight of each product combination on my product page. Currently, I have something like this: {l s='Weight: ' js=1}{sprintf("%1\$u",$product->weight)}&nbsp{Configuration::get('PS_WEI ...

In React, the entire component refreshes every time the modal is opened

<ThemeProvider theme={theme}> <GlobalStyle /> {componentName !== 'questionaire' && componentName !== 'activityResult' && <CardWrapper />} <ErrorModal ...

Unable to capture Metamask Errors

I am attempting to invoke a smart contract using ethers.contract and the signer from ethers.providers.web3Provider to leverage MetaMask. If the transaction fails, I want to capture the error and either retry or invoke a different function. However, my proj ...

Utilizing JSON data to generate an HTML webpage showcasing a collection of community districts through the power of JavaScript

As a beginner in javascript, I am working with a JSON file that contains an array of objects. Each object includes two properties: a borough and mappings. Mappings have two sub-properties called macro and neighborhoods. The macro represents a larger neighb ...

Select multiple options by checking checkboxes in each row using React

Is it possible to display multiple select checkboxes with more than one per row? For example, I have four options [a, b, c, d]. How can I arrange it to have 2 options per row, totaling 2 rows instead of having 1 option per row for 4 rows? ☑a ☑b ☑c ...

Problem arises with table nth-child selector following the addition of grid-gap

Our current table looks like this: The first row has a background color and the second row is white - which is correct. Now I would like to align the attributes to the right. I added the following code to the table: .table-wrapper tbody { font-size: ...

Is there a way to retrieve the ngModel reference of a child element within a directive's

I am currently utilizing bootstrap-colorpicker along with an angular directive in my project. Within my form, there is a colorpicker that I want to monitor for any changes. However, since the colorpicker jQuery plugin updates the value of the colorpicker, ...

Tips on showcasing the elements within a div container using flexbox

Seeking advice on positioning items/cards using flexbox in my initial react app. The issue lies with the div within my card component where applying display: flex; turns every card into a block (column-like) structure, flexing only the content within each ...

Tips for enabling custom object properties in Chrome DevTools

In my typescript class, I am utilizing a Proxy to intercept and dispatch on get and set operations. The functionality is working smoothly and I have successfully enabled auto-completion in vscode for these properties. However, when I switch to the chrome d ...

Ensuring that the text box only accepts the letters A, B, and C is essential for

Could you please help me with validating a text box? I would like to set it so that the user can only enter either A, B, or C. If they input D to Z or any other characters, I want a popup message to appear asking them to Enter A, B, or C. Would you recom ...

Next.js: Dealing with special characters in YouTube video API snippet titles

Trying to find the perfect video snippet title without any special characters. Accessing the API: https://www.googleapis.com/youtube/v3/search, along with specifying snippet. The current output for snippet.title is as follows: I&#39;M GONNA CARRY ...

Encountering the error "ReferenceError: Cannot access 'data' before initialization" during deployment on Vercel

I encountered a problem with my project after trying to implement dynamic routing. Initially, everything was working fine locally and during deployment. However, when I attempted to incorporate dynamic routing, errors started to occur. Unfortunately, I am ...

Is there a way to horizontally center Material UI Switch and its icon props?

I'm using Material-UI to implement a Switch component on my project. This particular component allows for the addition of icons, however, I've encountered an issue with alignment when including them. Is there a way to horizontally center align b ...

Creating a multipart/form-data POST request in Angular2 and performing validation on the input type File

I am working on sending an image (base64) via a POST request and waiting for the response. The POST request should have a Content-Type of multipart/form-data, and the image itself should be of type image/jpg. This is what the POST request should look like ...

Mastering the art of crafting and managing NodeJS promises with finesse

Currently, I am utilizing ExpressJS for handling APIs and heavily rely on promises for managing asynchronous requests such as external API calls and database queries. While this approach works well in most cases, it tends to clutter the code with numerous ...

Automatically submitting a form in React.js based on certain conditions being met

Does anyone have experience with React login and register form buttons that trigger Redux actions? I'm facing an issue where both actions are being dispatched at the same time when certain conditions are met. Here is my code snippet: const LoginPage ...

Error 500 on Firebase: Issue solving "firebase" in "firebase.js" not resolved

Struggling to incorporate Firebase into my latest React project, I keep encountering the dreaded "The development server returned response error code: 500." Despite creating a firebase.js file to house my Firebase configuration details, I am at a loss as ...

Learn how to assign unique IDs to each input radio field in a Grails GSP radiogroup

Is there a way to assign a unique id for each input attribute in a GSP Grails application? <g:radioGroup id="x"> ${it.label} ${it.radio} </g:radioGroup> It seems that using id="x" is not functioning as expected. ...

Tips for using the ternary operator to fetch data from the Github API with three conditions

Is there a way to use ternary operators for 3 conditions in my code? I am fetching data from the GitHub API using Axios. The first condition is for when the data is being fetched, where I want to show a loading screen. The second condition is for displayin ...