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

I am currently seeking a way to validate if a variable corresponds to the choice made in the dropdown menu. Any suggestions on how to accomplish this task?

I have put together a simple drop down menu. My goal is to grab the currently selected value from the drop down list, store it in a variable, and display it in the console. The ultimate objective is to compare that variable with another one to determine if ...

The new mui v5 Dialog is having trouble accepting custom styled widths

I am facing an issue with my MUI v5 dialog where I cannot seem to set its width using the style() component. import { Dialog, DialogContent, DialogTitle, Paper, Typography, } from "@mui/material"; import { Close } from "@mui/icons- ...

Unable to process the post request

I've encountered an issue while attempting to redirect using the res.redirect() function. When I submit the form, it should insert the data into the database and then redirect me to the home root. However, instead of successfully redirecting, I'm ...

Retrieving entities from a text

I found a script on the Webdriver.io website that looks like this (adjusted for testing) const { remote } = require('webdriverio'); var assert = require('assert'); ;(async () => { const browser = await multiremote({ ...

Vue.js has encountered a situation where the maximum call stack size has been exceeded

I have implemented a method called cartTotal that calculates the total price of my products along with any discounts applied, and I am trying to obtain the final value by subtracting the discount from the total. cartTotal() { var total = 0; var di ...

Inserting HTML code into the polymer

This is my HTML code: <div id="setImgWrap"> <!-- The appended image will be displayed here --> </div> Here I am appending an image from JavaScript: this.addedImages = { imageURL:self.downloadURL }; this.$.setImgWrap.append('& ...

Counter is effective for the initial post, yet it does not function properly for the subsequent post

Can anyone help with an issue I'm having with my JavaScript counter? It works for the first comment, but not the second one. This problem persists whether I use PHP or JavaScript. Below is the JavaScript code for the counter: var count = (function() ...

Are there specific mathematical algorithms that lend themselves well to creating responsive HTML designs?

Tired of constantly guessing the percentage values to use with a specific number of divs and other elements in my design. I am looking to understand the mathematical calculations that determine the scaling required for different elements in order to main ...

Leveraging Javascript within Objective-C

Can you help me understand how to implement this JavaScript code in Objective-C? var theFormId = $('form').filter(function() { return this.innerHTML.indexOf('forgot your password') != -1; }).attr('id'); Is there a way to int ...

Mastering the Implementation of Timetable.js in Angular with TypeScript

I am currently working on integrating an amazing JavaScript plugin called Timetable.js into my Angular6 project. You can find the plugin here and its repository on Github here. While searching for a way to implement this plugin, I stumbled upon a helpful ...

What is the best way to delete markers from a leaflet map?

I need to remove markers from my map. I am looking to create a function that will specifically clear a marker based on its ID. I am utilizing Leaflet for the map implementation. Here is my function: public clearMarkers(): void { for (var id in this. ...

Is it feasible to utilize the return value of an Async call to display or conceal an alert message?

Before this gets closed as a duplicate, I have searched through numerous threads on the forum that do not address my specific question. Please take the time to read. Here is the scenario: when a user clicks a button, JavaScript needs to validate whether t ...

Ensuring data validity in Angular 2 before enabling a checkbox

In my form, there is a checkbox for admins to edit user accounts. Each user object includes a boolean value isAdmin. I am trying to prevent users from editing their own account while still allowing them to view the values. However, no matter what I try, I ...

managing nested JSON arrays in JavaScript

I have a straightforward task with handling a simple array that is divided into two parts: a group of vid_ids and a single element named page. Initially, I was iterating through the vid_id array using a for loop. However, upon adding the page element, I en ...

Is there a way to pass locale data using props in VueJS Router?

To access hotel data, the URL path should be localhost:8080/hotel/:id (where id is equal to json.hoteID). For example, localhost:8080/hotel/101 This path should display the specific data for that hotel. In order to achieve this, we will utilize VueJS vu ...

Transform the string into an array with each element surrounded by square brackets

Looking for a solution to extract values from a string containing square brackets and store them in an array? Check out this example: $inputString = "['A'|'AA']['B'|'BB']['C'|'CC']"; The desired ...

shallow rendering does not recognize this.props as a function

I'm currently facing an issue while trying to test my (legacy) component using jest/enzyme. Here is a snippet of the component: export default class MyComponent extends Component { constructor( props ) { super( props ); this.handl ...

Synchronizing the DOM with the Database in a React Component/View: A Step-by-Step

I recently developed a list component in React, but I'm facing two significant challenges. Although the item gets removed from the database, the change is only visible after refreshing the page. You might have noticed that the list number or ID colu ...

Having trouble integrating NEXT AUTH with Firebase due to an error: "Cannot import statement outside

Let's take a look at our firebase configuration file: import { getFirestore } from "firebase/firestore"; export const firebaseConfig = { apiKey: process.env.FIREBASE_API_KEY, authDomain: process.env.FIREBASE_AUTH_DOMAIN, projectId: pr ...

Tips for avoiding the persistence of an old array on the screen after refreshing and showing the new, updated array

Currently, my task involves displaying array values on a webpage. The array data is sourced from a real-time database in Firebase. After adding new values to the array or inputting another value into the database on the previous page, we are redirected to ...