Sort array of objects alphabetically and move objects with value to the beginning

I have a dataset that consists of different arrays of objects. When I log myData, the output looks something like this:

[
  {
    name: 'Cdb',
    image: 'xxx',
    coll: 'xxx'
  },
  {
    name: 'Bcd',
    image: 'xxx',
    coll: 'xxx',
    url: 'myurl'
  }
]
[
  {
    name: 'Abc',
    image: 'xxx',
    coll: 'xxx'
  }
]

My goal is to sort these objects alphabetically based on the value of name. Additionally, if an object has the parameter url, it should be placed at the beginning of the sorted list.

The desired output should look like this:

    name: 'Cdb',
    image: 'xxx',
    coll: 'xxx',
    url: 'myurl'

    name: 'Abc',
    image: 'xxx',
    coll: 'xxx'

    name: 'Bcd',
    image: 'xxx',
    coll: 'xxx'

I've attempted various approaches, including the following code snippet, but none seem to work as expected:

var myData = props?.data

console.log(props?.data)

if(props.data){
  // Sort with objects having url first and then alphabetically
  myData = props.data.sort(function(a, b){
    return b.url ? 1 || (a.name < b.name) : -1;
  })
}

Answer №1

Utilizing !url as a binary value (0 or 1) and performing subtraction:

const arr = [{"name":"Cdb","image","xxx","coll":"xxx"},{"name":"Bcd","image":"xxx","coll":"xxx","url":"myurl"},{"name":"Abc","image":"xxx","coll":"xxx"}]

arr.sort((a, b) => !a.url - !b.url || a.name.localeCompare(b.name));
  
console.log(arr)

This logic states that if only one of the compared objects contains the url property, it should be placed before the other. If both have it or neither do, then their name values determine order.

Therefore, when multiple objects include the url property, they will also be sorted based on their name values.

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

Using JavaScript to create an image slider

My image slideshow with prototyping is not working properly and I am struggling to fix it. I have tried binding the setInterval function but it's not working. I also attempted to wrap it, but that didn't work either. What should I do to solve thi ...

MUI - Material-table/core - Checkbox selection malfunctioning on click event

UPDATE : The matter also pertains to Material Ui's Data table. I attempted to replicate the issue using the provided example in the documentation but encountered the same problem. I have been struggling with an issue related to the selection feature ...

Creating a custom comparison method between two select dropdowns using the jQuery Validation plugin

In my HTML code, I have two select elements: <label for="h_slat_type">Horizontal Slat Type</label> <select name="h_slat_type" id="h_slat_type"> <option disabled="disabled" selected>Select</option> ...

JavaScript code not functioning on WordPress website (no impact)

I've encountered a strange problem. Here is the code snippet: (function($){ $("#maps1").hover( function(){$("#kontakt_os_1").hide();} ); $("#maps2").hover( function(){$("#kontakt_os_2").hide();} ); $("#maps3").hover( ...

MATLAB tutorial: Efficiently summing matrix rows using an index vector

When dealing with two column vector indices and values, the accumarray(indices, values) function can be utilized to sum duplicate values, meaning entries of the vector values that share common indices. Is there a method that operates similarly when the ve ...

Switching measurement unit to jQuery when retrieving image weight

After coming across a solution on this question, I am looking to determine the weight of an image from a file input. The solution I found displays the result in MiB (Mebibyte) unit. Is there a way to show the image weight using the same code, but in a diff ...

How can I use JavaScript to show a div upon clicking an input element?

I am looking to make a block div visible when an input field is clicked. <input class="indifferent" type="radio" name="decision" value="indifferent"> Indifferent </br> <div class="input" style="display: none;"> Please assist with our com ...

Unable to display canvas background image upon webpage loading

Currently working on a JavaScript project to create a captcha display on a canvas. The issue I'm facing is that the background image does not load when the page initially opens. However, upon hitting the refresh button, it functions as intended. Here& ...

Transmitting a variable string from JavaScript to PHP through AJAX

How can I pass a variable value from an HTML page using JavaScript to PHP? In my index.php file, I have the following code: $amount = $_GET['pricenumb']; echo $amount; Here is the JavaScript code I used to call on click of a button and send th ...

When attempting to view the PDF file, it appears completely void

After spending countless hours on this task, I'm still not making any progress. My goal is to download a PDF file from my server while currently running the operation on localhost. However, whenever I open the downloaded PDF, all I see is a blank whit ...

Dynamic jQuery slideshow with unique starting point

My photo collection is displayed in a list format like this: <ul class="slideshow"> <li><img src="images/slideshow/slide0.jpg" alt="" /></li> <li><img src="images/slideshow/slide1.jpg" alt="" /></li> & ...

What could be causing IE11 to cut off my JavaScript file prematurely?

Edit: I believe I have resolved the issue, and it seems to be more related to Angular than I initially thought. The problem was caused by a fat arrow in the script, which was not easily visible due to code minification. This script is a global script that ...

External IPs cannot access Node.js

I am facing an issue with my Amazon EC2 Server where I have set up a node js server. It is not accessible from the outside using the public DNS, but it can be accessed from the same instance (localhost). Any assistance in resolving this problem would be gr ...

Function that observes with the pipe syntax

Is it possible to apply map, switchMap, or any other operator in conjunction with a function that outputs an observable? The objective here is to transform the result of the observable function and utilize that value during the subscription to another ob ...

Tips for extracting the chosen text during a 'change' event

I need to access the text of the currently selected object. When I use $(this).text(), I end up getting all available selections I have attempted the following methods without achieving the desired result: $(this).text() $(this).selected() $(this).se ...

How big is the array size in the WebAudio API data?

Exploring the visualization of waveform and FFT generated by the audio stream from the microphone through the WebAudio API. Curiosity strikes - what is the size of each data array available at a given moment? Delving into the getByteTimeDomainData, it men ...

Issue with variable not being refreshed within requestJS's data event

I have been attempting to store the response from a URL in a variable for caching purposes and then send it upon subsequent requests. I am currently writing to the variable during the data event of the request. The variable does get updated, but I am encou ...

Issue with jQuery sortable serialization when dynamically adding content is not being recognized

I've been attempting to re-order a list through ajax on sortable update. However, when I add a new item to the list via ajax after the sortable has already been initialized upon page load, it fails to recognize the new item with the "serialize" functi ...

What is the best way to position a tooltip near an element for optimal visibility?

One div is located on the page as follows: <div id="tip"> Text for tip goes here... </div> And another one can be found below: <div class="element"> Text for element goes here... </div> There is also a piece of JavaScript ...

Sharing information between pages in React through Router

I am struggling to transfer a single string from one page to another using react router and only functional components. I have created a button that links my pages, but I can't seem to pass the string successfully. Here is an example of the code on th ...