JavaScript array sorting not functioning for specialized logic

I am facing an issue with sorting arrays. I have a custom logic for displaying the array where each object has a 'code' column with values ('A', 'B', or 'C'). The requirement is to sort the records to display 'B' first, then 'A', and finally 'C'.

Link to my code is available on StackBlitz.

Below is the code snippet:

list.sort(function (el1, el2) {
  if (el1.codeNumber > el2.codeNumber) {
    return 1;
  }
  if (el1.codeNumber < el2.codeNumber) {
    return -1;
  }

  return 0;
});

Answer №1

To streamline the code, consider using an object to arrange items based on a specific code.

const
    list = [{ name: 'Bala', age: 21, code: 'A' }, { name: 'Bala', age: 22, code: 'A' }, { name: 'Bala', age: 23, code: 'C' }, { name: 'Bala', age: 24, code: 'A' }, { name: 'Bala', age: 25, code: 'B' }, { name: 'Bala', age: 26, code: 'B' }, { name: 'Bala', age: 27, code: 'B' }, { name: 'Bala', age: 28, code: 'A' }, { name: 'Bala', age: 29, code: 'B' }, { name: 'Bala', age: 30, code: 'C' }, { name: 'Bala', age: 31, code: 'C' }, { name: 'Bala', age: 31, code: 'C' }, { name: 'Bala', age: 28, code: 'A' }],
    order = { B: 1, A: 2, C: 3 };
    
list.sort((a, b) => order[a.code] - order[b.code]);

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

How can I resolve a promise that is still pending within the "then" block?

Here is a piece of code that I have written: fetch(`${URL}${PATH}`) .then(res => { const d = res.json(); console.log("The data is: ", d); return d; }) When the code runs, it outputs The data is: Promise { <pending> ...

Tips for sending a URL in form-data as a file with JavaScript or Axios

Currently, I am using Vue.js and Axios to send form data to a specific link. However, I encountered an issue where the file is not being sent and I am receiving an error message. The parameter 'file' had the following problems: file transferred w ...

Ways to clear TextField status

My question is about a Textfield. In the case where the state is null but the text field value is showing in the Textfield. <TextField style={{ width: '65%'}} id="standard-search" ...

The Node function will yield a BluebirdJS Promise

I've encountered a minor issue with this script. While it functions properly, the "runTenant" method is not returning a promise that needs to be resolved with "all()". Here's the code snippet in question: Promise.resolve(runTenant(latest)).then ...

Minimize CPU consumption in your threejs application

I've been working on a project where I'm coding Snake in Threejs (I know there are simpler methods). Everything works smoothly until the snake reaches a certain size, causing CPU usage to spike to 50% or more and freezing the entire browser tab. ...

Looking to add some movement to your website? Learn how to make an image track your mouse pointer in a specific section of your webpage

I'm just starting out with web design and javascript, so please be patient. My goal is to have an image follow the mouse pointer only when it's within a specific section of my website. I've managed to make the image track the mouse cursor ...

What is the best way to pass the username and token data from a child component to its parent component

Hey, I'm currently working on a login app in React where the login component is a child of the app. My goal is to send back the username and token to the parent component once a user is logged in, so that I can then pass this information to other chil ...

Receiving an alert in VSCode regarding the usage of CharAt function in conjunction with Vuejs

While attempting to extract the first character of a computed property, I utilized the charAt() function. Despite the fact that it is functioning correctly, I am receiving a warning from VSCode indicating that it is not the correct usage. computed: { ...m ...

"The 'BillInvoice' object must be assigned a primary key value before it is ready for this relationship" - Error Message

There is an issue in my Django project related to the creation of a BillInvoice and its associated BillLineItem instances. The error message I'm receiving states: "'BillInvoice' instance needs to have a primary key value before this re ...

What is the process for incorporating a particular item into a child's possession?

I've got a structure that looks like this: items: [ { title: 'Parent', content: { title: 'Child1', content: [ ...

Issue with Javascript functionality not persisting after page reload initiated with a href = '#'

I am facing an issue with a button on my webpage that is meant to redirect and reload the home page. However, after redirection to '#', my JavaScript seems to stop functioning correctly. Currently, my JavaScript code is enclosed within window.on ...

Utilizing Vue JS for applying multiple filters on a single array

I'm currently facing challenges in optimizing my code. I've successfully created dynamically generated objects from an array, implemented a search function, and had a working filter (just one) at some point. However, my attempt to chain the filte ...

What could be causing the absence of pagination links on my website?

While attempting to adjust the width of the images, I noticed that the navigation pager below (pages 1,2,3) unexpectedly disappeared. As a CSS beginner, I'm unsure why this happened and how to resolve it. The code for the navigation is still present, ...

What is the reason for having to add my IP to the white-list daily?

As a beginner, I am delving into the world of back-end development with Node.js, Express.js, and Mongoose for educational purposes. My database is hosted on Atlas-Mongo DB. Initially, everything seemed to be running smoothly as I configured it with the fre ...

Guide on implementing the Translate service pipe in Angular 2 code

So here's the issue... I've integrated an Angular 4 template into my application which includes a functioning translate service. The only problem is, I'm unsure of how to utilize that pipe in my code. In HTML, it's as simple as adding ...

Understanding the significance of an exclamation point preceding a period

Recently, I came across this code snippet: fixture.componentInstance.dataSource!.data = []; I am intrigued by the syntax dataSource!.data and would like to understand its significance. While familiar with using a question mark (?) before a dot (.) as in ...

Vue - Error Message from Eslint Regarding Absence of Variable in Setup Function

Interestingly, the Vue.js documentation strongly recommends using the <script setup> syntax of the Composition API. The issue with this recommendation is that the documentation lacks depth and it conflicts with other tools (like eslint). Here is an e ...

My experience with jquery addClass and removeClass functions has not been as smooth as I had hoped

I have a series of tables each separated by div tags. Whenever a user clicks on a letter, I want to display only the relevant div tag contents. This can be achieved using the following jQuery code: $(".expand_button").on("click", function() { $(th ...

Various inquiries utilizing varying parameters

Initially, I am receiving instructions from a mysql query. Receiving Instructions function getAllInstructions(req,res){ let mysqlQuery = `SELECT * FROM instructions where id = '` + req.params.id + "'"; connection.query(mysqlQuery, funct ...

Shared codes are compatible with both C and Javascript programming languages

Within the scope of this project, data will be retrieved from the server in either JSON or XML format. There are two separate client applications that will handle the data processing, with one being web-based and written in JavaScript, while the other is ...