Sort the array of objects based on the presence of a specific property

I have a list of teachers, each with a user property that includes an image. This image property can either be a string or null. How can I sort the list based on the user.image property?

Below is an example of the data structure.

const teachers = [
    {
        id: 1,
        user: {
            id: 10,
            image: "image.jgp"
        }
    },
    {
        id: 3,
        user: {
            id: 30,
            image: null
        }
    },
    {
        id: 2,
        user: {
            id: 20,
            image: "image.jgp"
        }
    },
    {
        id: 4,
        user: {
            id: 40,
            image: null
        }
    },
]

Answer №1

If you want to sort an array based on the presence of the image property, you can utilize the Array.sort method:

const teachers=[{id:1,user:{id:10,image:"image.jgp"}},{id:3,user:{id:30,image:null}},{id:2,user:{id:20,image:"image.jgp"}},{id:4,user:{id:40,image:null}];

const sorted = teachers.sort((a, b) => b.user.image === null ? -1 : 1)

console.log(sorted)

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 has occurred in the Shadow Dom due to the inability to access the property 'style' of an

While working on a component using shadow DOM, I encountered the following error in the console: "Cannot read property 'style' of undefined". This issue seems to be related to my HTML code in PHP. The main challenge I am facing is figuring out ho ...

It's essential to ensure that this property remains responsive, whether through the data option or by initializing the property for class-based components

This code snippet contains the template and path information. <template> <div class=""> <c1 :text="message1"></c1> <c1 :text="message2"></c1> </div> </templa ...

Displaying a submenu upon hovering within its designated CSS region

I'm encountering an issue with my submenu. It's supposed to appear when hovering over the parent menu li, but it also shows up when the mouse hovers over its area. Let's take a look at some images. First screenshot below shows that it works ...

customize Form Modal Bootstrap with AJAX Chained Dropdown for pre-selected options

I am facing an issue with a chained dropdown on a bootstrap modal, Here is the code snippet: function changeDetail(id) { var id = id; $('#edit').prop('hidden', true); $('#modal_form').prop('hidden', fa ...

What is the best approach for showcasing the contents of an array with class attributes in TypeScript?

Here is an example code snippet for adding a single item from a pre-written array to a table. In this case, we have a simple name element so only one "< td>${people[i]}< /td>" tag is needed to display the names. let people: string [] = ["Jack" ...

Problems Arising from the Content Menu and Tab Opening Features of a Chrome Extension

I am encountering an issue with the code below not displaying the context menu when text is selected on the webpage. Currently, when I select text, the context menu fails to appear. Code function getword(info,tab) { if (info.menuItemId == "google") ...

The function "element.join" is not a valid function

Currently, I am working on a project where I need to write a list of IDs into an external file using Node.js. Despite successfully creating the file with the nodejs file system and attempting to write into it, my program crashes and displays the error mess ...

The crossIcon on the MUI alert form won't let me close it

I am facing an issue with my snackBar and alert components from MUI. I am trying to close the alert using a function or by clicking on the crossIcon, but it's not working as expected. I have used code examples from MUI, but still can't figure out ...

Encountering CORS policy error preventing localhost from running

While working on my Net SuiteCommerce Advanced E-commerce webstore, I encountered an error message when running localhost. Despite conducting research on Stackoverflow and other websites, I have been unable to find a satisfactory solution. I attempted to ...

Utilizing the tilde symbol (~) within a link that is generated dynamically

I want to dynamically create sub-menu items with links and URLs using JavaScript. However, I'm encountering an issue where the URL doesn't interpret the tilde (~) as the root directory but simply appends it to the current URL. Here's a snip ...

Change the background color of the MUI ToggleButton that is currently selected

I need help figuring out how to change the background color of a selected toggle button. Currently, the buttons are functional but do not visually indicate when one is selected. I would like the first button (Btn 1) to have a default color, and if the us ...

Show detailed information in a pop-up window

Javascript $(function() { var dmJSON = "clues.json"; $.getJSON( dmJSON, function(data) { var idx=1; $.each(data.details, function(i, f) { var myid = 'mypop'+String(idx); idx++; var $popup="<popu ...

Combine a PHP function that generates an array with another array

I'm currently working on developing an OpenCart store that follows the mcv design pattern. I am in need of a model function that returns an array, but within that array, I must make a call to another function that also returns an array. Unfortunately, ...

Using VueJS Computed Property along with Lodash Debounce

I have been encountering a slowdown while filtering through a large array of items based on user input. I decided to implement Lodash debounce to address this issue, but unfortunately, it doesn't seem to be having any effect. Below is the HTML search ...

Executing asynchronous functions within a loop using useEffect

My current scenario is as follows: export default function Component({ navigation }) { const [ item, setItem ] = useState([]); useEffect(() => { AsyncStorage.getItem('someItem') .then(data => JSON.parse(data)) ...

Instructions for correctly performing a "not equal" string comparison within an array in bash, followed by removing the specified element

I'm struggling with comparing the last three characters of strings in an array using a != string comparison. My goal is to delete elements that don't match, but my current code isn't giving me the expected results. I know there's a mist ...

How can I convert Typescript absolute paths to relative paths in Node.js?

Currently, I am converting TypeScript to ES5/CommonJS format. To specify a fixed root for import statements, I am utilizing TypeScript's tsconfig.json paths property. For instance, my path configuration might look like this: @example: './src/&ap ...

Unlocking the Power of Marionette.CompositeView: Passing Parameters to Marionette.ItemView

Is there a way to access the app.vent from Marionette.ItemView? One solution might be to pass a parameter (app.vent) to Marionette.ItemView from Marionette.CompositeView. Here's the code snippet: // view/compositeView.js define([ 'marionet ...

Exploring VueJs 3: Strategies for loading and implementing actions on a component before mounting

Briefly: Can a virtual node be created outside of the DOM to preload images, seek videos... without ever being mounted in the real DOM? Detailed version: I want to ensure that the next slide appears only when it is fully initialized for a slideshow in Vu ...

Typescript is experiencing an error due to the use of attr("disabled", false) causing a disruption

Within my ts file, I'm using the code snippet below: $('input[type=hidden]').attr("disabled", false); The code functions as intended, however, an error persists: Argument of type 'false' is not assignable to parameter of typ ...