Steps for sorting an array of objects and selecting the first element1. Create an array of

Is it possible to sort an array of objects in JavaScript while specifying the first element? Here's an example:

Initial data in JavaScript

{title: 'test 1', text: 'aa'},
{title: 'test 2', text: 'bb'},
{title: 'display first', text: 'this is an example'},
{title: 'test 4', text: 'dd'}

After sorting

var elementToDisplayFirst = "display first";

{title: 'display first', text: 'this is an example'},
{title: 'test 1', text: 'aa'},
{title: 'test 2', text: 'bb'},
{title: 'test 4', text: 'dd'}

Thank you!

Answer №1

Implement a custom sorting approach

var arr = [{
    title: 'Fuchsia',
    text: 'paniculata'
  },
  {
    title: 'Panthera',
    text: 'leo'
  },
  {
    title: 'Canis',
    text: 'lupus'
  },
  {
    title: 'display first',
    text: 'Forrest Gump'
  },
  {
    title: 'Felis',
    text: 'silvestris'
  }
]

arr.sort(function(a, b) {
  if (a.title === 'display first') {
    return -1
  } else if (b.title === 'display first') {
    return 1
  } else return  a.title < b.title ? -1 : a.title > b.title ? 1 : 0;
})

console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To achieve a descending order based on the boolean values of true (1) and false (0), you can verify if the title matches the desired string and then calculate the inverted delta between them.

var array = [{ title: 'test 1', text: 'aa' }, { title: 'test 2', text: 'bb' }, { title: 'display first', text: 'this is an example' }, { title: 'test 4', text: 'dd' }]
    first = "display first";
    
array.sort(({ title: a }, { title: b }) => 
    (b === first) - (a === first) ||
    a > b || -(a < b)
);

console.log(array);
.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

Ways to attach an event listener to a useRef hook within a useEffect hook

As I work on creating a custom hook, I am faced with the task of adding an event listener to a ref. However, I am uncertain about how to properly handle cleaning up the event listener since both listRef and listRef.current may potentially be null: const ...

Error: The JQUERY autocomplete is throwing an uncaught type error because it cannot read the property 'length' of an undefined value

These scripts are being utilized at this source I have implemented jQuery Autocomplete to search for users in my database. Below is the controller code returning Json: public function searchusers1() { if ($_GET) { $query = $this -> input ...

"Enhance your React project with dynamic filtering capabilities using Ant Design's Table

When attempting the code below, I encounter an error related to columns: { title: "Gruppe", dataIndex: 'group', filters: [ this.state.dropdownItems.map((item) => ({ text: item.group, value: item.group ...

What is the reason behind the inconsistency of calling a function on click not always functioning properly in Chrome and FF, while working seamlessly in IE?

Consider a scenario where the code below is being used: <HTML> <HEAD> <SCRIPT> function myFunction(atlasTrackingURL) { var atlasURL = atlasTrackingURL; if (!atlasURL) return; //Creating a cache busting mechanism ...

Receive updates on new emails with the Zimbra mail server

In the Zimbra mail server, there are blacklists and whitelists that determine whether to block or allow new incoming emails. However, the process of blocking an email this way can be inconvenient. I am interested in creating a plugin for the Zimbra mail se ...

Troubleshooting a Vertex AI Fine Tuning Job in Node.js: Does Service Account Lack Required Permissions for the Task?

I am currently utilizing a pipeline job to fine-tune a text-bison model with Vertex AI on Google Cloud Platform. The API I am using is logged in with a specialized service account that has been assigned the roles of Vertex AI Service Agent and Service Acco ...

Is there a way to make a string evaluate inline using JavaScript and React?

In my function, the following code works perfectly: console.log(theme.colors.blues[1]); To make the last part dynamic, I tried the following approach: const getColor = (theme, passedColorProp) => { console.log(theme.colors.[passedColorProp]); }; g ...

"Utilizing Typescript's generic type declaration feature to pass type

Imagine this scenario with a specific type and a generic: type Data = { item: number }; type Generic<T> = { obj: T; }; Now, let's create an instance of this generic: const test: Generic<Data> = { obj: { item: 0 } }; When accessing tes ...

`json_encode does not output a UTF-8 character`

I send an AJAX request to the PHP server, and receive back an array encoded in JSON. This array has only two indexes. When I log it using console.log(), this is what I see: {"1":"\u00d9\u0081\u00db\u008c\u00d9\u0084\u0 ...

Creating an AngularJs directive to alter input formatting

I am looking to achieve the following: Within my controller model, I have a date object that I want users to be able to modify. I need to provide them with two input fields - one for modifying the date and the other for modifying the time. Both input fiel ...

angular add to the end the most recent compiled element

Looking to incorporate a custom event into the fullcalendar plugin. eventRender: function(event, eventElement) { scope.tmp = { time: $time, $title: $title, crest: event.clubCrest, statusKey: statusKey }; scope.data ...

Next-auth encounters a TypeError [ERR_INVALID_URL] when attempting to use an invalid URL exclusively in the production

When I attempt to sign in using next-auth in my Next.js app in production mode by running the command `yarn build && yarn start` on my local machine, the app fails. The error message displayed in the terminal is: TypeError [ERR_INVALID_URL]: Invalid URL ...

Problem with inserting data into MongoDB

I am facing a challenge with my Mongo DB structure, which is structured as follows: db.users.find().pretty(); { "_id" : ObjectId("52b42b148ffa91f7ebbe8ebc"), "username" : "test", "password" : "test", "party" : [ "4988", "50 ...

Transmitting data using JavaScript to Spring server

I am facing a challenge of uploading an image to a server using Spring. The code snippet I am using to get the file is as follows: var file = $("#form-field-photo").get(0).files[0]; I have attempted several methods to post it, but so far, all my attempts ...

Creating a Class in REACT

Hello fellow coding enthusiasts, I am facing a minor issue. I am relatively new to REACT and Typescript, which is why I need some assistance with the following code implementation. I require the code to be transformed into a class for reusability purposes ...

What are some effective strategies for structuring code with AngularJS?

I'm currently working on an app that utilizes ui router to append all HTML data to the following tag: <div class="app" ui-view > However, I want to add a header and footer to my app. My question is, should I include them in the index.html lik ...

I am looking to implement a feature that will disable unchecked checkboxes based on certain conditions in a

Upon selection of an option from a dataset, an API call is triggered. The API response includes an object with a nested array, whose values are listed as checkboxes. Additionally, the API returns a key named choose(const name primaryMax) indicating the max ...

Custom validation preventing Ng-minlength from functioning correctly

I'm currently working on an angularJS project where I am trying to create a form for users to input their username. The application needs to validate if the username is available in the database and if it falls within a character length of 5 to 10. & ...

Angular 7 seems to be having trouble handling file submissions on forms

I'm facing an issue with submitting files along with a form in Angular. I tested my API using Postman and it worked fine, but when trying to implement it in Angular, I'm struggling to make it function correctly. Despite attempting various method ...

Leveraging jQuery template for JSON visualization

I've been struggling for days to understand how to render JSON data using jQuery templates with no luck. I was hoping someone could help me figure out where I'm making a mistake. The JSON data I am working with looks something like this: [{"pk" ...