Arrange the array in ascending order based on a specific value

Within my array, I have various objects of different types:

myArray = [
{state: "enabled", name: "zName"},
{state: "trying", name: "aName2"},
{state: "disabled", name: "aName3"},
{state: "disabled", name: "cName"},
{state: "disabled", name: "bName"}
]

My goal is to sort this array based on the following criteria:

  1. state equals $givenValue
  2. name should be arranged in ascending order for items that meet criterion 1

For instance, if I specify state == "disabled", the expected sorted array would be:

myArray = [
    {state: "disabled", name: "aName3"},
    {state: "disabled", name: "bName"},
    {state: "disabled", name: "cName"},
    {state: "trying", name: "aName2"},
    {state: "enabled", name: "zName"}
]

Unfortunately, I'm struggling to find a solution on my own. Could you provide assistance? Thank you.

Answer №1

To organize the array based on specific criteria (state == "disabled" and name in ascending order for items that meet the first criteria), utilize the Array.prototype.sort()

const myArray = [
  {state: "enabled", name: "zName"},
  {state: "trying", name: "aName2"},
  {state: "disabled", name: "aName3"},
  {state: "disabled", name: "cName"},
  {state: "disabled", name: "bName"}
];
const givenValue = "disabled";
function customSort(a, b) {
  if (a.state === givenValue && b.state === givenValue) {
    return a.name.localeCompare(b.name);
  } else if (a.state === givenValue) {
    return -1;
  } else if (b.state === givenValue) {
    return 1;
  } else {
    return 0;
  }
}
myArray.sort(customSort);
console.log(myArray);

Answer №2

To establish a specific sequence, I suggest creating an array with the values ["enabled", "trying", "disabled"]. By referencing the object value, you can easily retrieve the corresponding index from the array in order to sort them accordingly.

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

Halt the execution of any additional code

I have a favor to ask: Character.count({'character.ownerid': msg.author.id}, function (err, count) { if (err) { throw err; } if (count > 3) { err.message = 'Exceeded character limit'; //create error ...

When utilizing auth0, an error occurs during the grunt build process

I successfully developed a small project using AngularJS on my local machine without encountering any issues. However, when I attempted to build the project with Grunt, everything stopped working and an error occurred: vendor.ce3c01a3.js:2 Error: [$inject ...

jquery mouse event does not register on touch-based devices

I have a mouse move event set up to scroll a div. However, when I try to access the functionality using a tab it does not work. How can I integrate this functionality onto a touch device? $(document).ready(function(){ $('#tim').on('mous ...

Tips for effortlessly enlarging an element

When you click on "#sidebarnav>li", the following happens: 1) The second child of it - <ul> element will expand and its class toggles between "collapse" and "collapse in". 2) "#sidebarnav>li" will receive the "active" class. 3) The "aria-ex ...

Tips for shrinking the circumference of a circle

Currently, I have a circular div that has been styled using CSS animations. My goal is to keep the size of the circle consistent when it moves to the bottom, but reduce its size when it bounces back to the top. I am uncertain if this can be achieved solely ...

I am curious about why I am unable to utilize inline functions in component props. Could you please provide a detailed explanation and perhaps give an example to illustrate? Furthermore, what is

Please take note: The component prop accepts a component, not a render function. Do not pass an inline function (e.g. component={() => }), as this will cause your component to unmount and remount, losing all state when the parent component re-renders. F ...

Generate slanted projection mapboxgl

Trying to develop a building simulator based on zoning codes. I can measure values, create floors, but struggling to extrude diagonally or create a perpendicular plane to the floor for evaluating angles from the street to limit building height (see image 2 ...

Guide to encoding data using a multidimensional array in JSON format

I have an array that looks like this: array { [0] => {"ID":"343","name":"John","money":"3000"} [1] => {"ID":"344","name":"Erik","money":"2000"} [2] => {"ID":"346","name":"Ronny","money":"3300"} } My goal is to transfer this data from ...

Encountering an Unresolved Runtime Issue: TypeError arises when attempting to access properties of undefined (specifically 'call') while utilizing the Image component in next.js

I'm currently experimenting with the Image component offered by next.js. This Is My Basic Header Component import Image from 'next/image' import React from 'react' import myImage from '../assets/IMG-20221115-WA0001.jpg' ...

Web Scraping ASU Courses using Node.js

I'm a beginner when it comes to Node.js, so please forgive me if I sound confused. Currently, I am attempting to scrape course information from ASU's course catalog (https://webapp4.asu.edu/catalog/) using tools like Zombie, Node.IO, and the HTT ...

The json_decode function in PHP unexpectedly returns null when provided with valid JSON input

I am attempting to send a JSON object using AJAX post in JavaScript as shown below: $.ajax({ type: 'POST', url: 'testPost.php', data: {json: cond}, dataTyp ...

Something seems to be amiss with the validation functionality in jQuery

After creating a simple form with input fields and a button, I added validation to display an error message when clicking the apply button without filling out required values. However, the code is not functioning as intended. Even though error messages are ...

Display/Conceal content with JQuery on a PHP webpage

I am having trouble with the following code. My intention is to show/hide the content between the #info id when clicking buttons, but nothing seems to be happening. Could you help me identify the issue? echo '<script> $( "#show' . $r ...

What is the best way to interact with a checkbox that has a label using Selenium in Node.js?

My HTML document contains multiple checkbox classes with different texts for each checkbox name. Here is a snippet of the HTML code: <div class="col-md-12 syllabus-div-1"> <h4 class="vertical-spacing">Coaching<i class="fa fa-graduation- ...

Updating the Highcharts chart when new data is available

Utilizing Highcharts, I am looking to have this chart update every second. Here's my current setup: JSFiddle I've implemented a timer with window.setInterval(updateChart, 1000); which successfully updates data each second. However, I'm uns ...

I found myself pondering the significance of the {blogs: blogs} in my code

app.get("/articles", function(req, res){ Article.find({}, function(err, articles){ if(err){ console.log("an error occurred!!!"); }else{ res.render("homepage", `{articles: articles}`); } }); I created this c ...

Utilizing Google Script to extract information from Gmail emails and transfer it to Google Sheets

I am facing a challenge with extracting data from an email and inputting it into a Google Sheet. While most of my code is functioning properly, I'm struggling with the regex section due to lack of expertise in this area. Below is a snippet of the HTM ...

Retrieve the text input from the text field and display it as

Is there a way to display what users enter in a textfield when their accounts are not "Activated"? Here's an example: if(active == NULL);{ //I've attempted the following methods. //In this scenario, 'username' is the name of ...

What is the best way to eliminate the border color on a drop-down menu's bottom border?

I need help removing the border color from a dropdown with the style border-bottom: 1px solid rgba(0, 0, 0, 0.42); After debugging, I discovered that it is originating from the class MuiInput-underline-2593. However, the CSS class MuiInput-underline-2593 ...

Permanent Solution for HTML Textbox Value Modification

https://i.sstatic.net/nB58K.pngI'm currently working on a GPS project where I am attempting to capture the altitude (above sea level) value in textbox1 and convert it into a ground level value displayed in textbox2. In this scenario, the GPS Altitude ...