Tips for organizing an array of objects in JavaScript according to a specific attribute value?

I'm trying to sort an array of notification objects in decreasing order of severity: Error > Warning > Information.

For example:

var notificationArray = [ {
    code : "103",
    severity : "Error"
}, {
    code : "104",
    severity : "Information"
}, {
    code : "109",
    severity : "Error"
}, {
    code : "403",
    severity : "Warning"
}, {
    code : "510",
    severity : "Information"
}, {
    code : "114",
    severity : "Warning"
}, {
    code : "144",
    severity : "Error"
}, {
    code : "413",
    severity : "Warning"
} ];

What's the best way to ensure this array is always sorted by severity?

P.S. I've seen other threads on sorting arrays of objects, but they mostly focus on unicode sorting rather than comparing against a fixed value like I need. Apologies if this question is repetitive.

Answer №1

To organize notifications based on severity, you can use an order object.

var notificationArray = [{ code: "103", severity: "Error" }, { code: "104", severity: "Information" }, { code: "109", severity: "Error" }, { code: "403", severity: "Warning" }, { code: "510", severity: "Information" }, { code: "114", severity: "Warning" }, { code: "144", severity: "Error" }, { code: "413", severity: "Warning" }, { code: "131", severity: "Error"}],
    order = { Error: 1, Warning: 2, Information: 3 };

notificationArray.sort(function (a, b) {
    return order[a.severity] - order[b.severity];
});

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

Answer №2

Consider the following approach:

var errors = notificationArray.map(function(message) {
  return message.severity === 'Error';
});
var warnings = notificationArray.map(function(message) {
  return message.severity === 'Warning';
});
var infos = notificationArray.map(function(message) {
  return message.severity === 'Information';
});

var sortedMessage = errors.concat(warnings).concat(infos);

I cannot guarantee if this method is quicker than @NinaScholz's solution, but it might be easier for you to follow.

Answer №3

Assign a priority to each level of severity

EXAMPLE :

var priority = {
    low: 0,
    medium: 1,
    high: 2, 
}

Next, organize the notifications array according to the priority of each severity level

notificationArray.sort(function(a, b) {
    var p1 = priority[a.severity.toLowerCase()];
    var p2 = priority[b.severity.toLowerCase()];
    return p2 - p1;
});

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

Error code E11000 is thrown due to a duplicate key in a Node.js application

Whenever I input data on the webpage, it syncs correctly with the database. However, when I attempt to fill out the same form again, an error occurs: { "code": 11000, "index": 0, "errmsg": "E11000 duplicate key error collection: test.creates i ...

Unable to locate the Chart object within the chartjs-plugin-labels.js file

Hello there, I am currently working on an Angular project where I want to incorporate a chart plugin. To achieve this, I executed the following commands: npm install angular2-chartjs npm install chartjs-plugin-labels Following that, I imported it into my ...

Displaying the initial element in an NgFor loop in Angular 2

Whenever I click on the "Add row" button, I dynamically generate a row of inputs and dropdowns. Upon clicking another button, the complete data is submitted and displayed in console.log as an array of objects, with each object representing a single row. C ...

How can I extract the JSON value as a string?

I have a scenario where I define two objects. The first object, BOB, has properties "name" with a value of "bob" and "height" with a value of 185. var BOB = { "name": "bob", "height": 185 }; The second object, PROPS, references the height property from ...

Building a query in Javascript by utilizing object keys and values: a step-by-step guide

I am looking to transform an object with various keys and values into a query string format, for example: obj1: { abc: "Abc", id: 1, address: "something" }. The challenge is that this object is generated dynamically, so the numbe ...

Avoid duplication of elements in Angular applications

Currently, I have a component that loads animated divs based on a datasource. *Note: In the example, I've used a lot of <any> because I haven't finalized the model yet. apiService.ts dataArray: Observable<Array<any>>; constru ...

Encountering an issue while attempting to fetch a value from a nested object property with VueJS Interpolation

I'm struggling to properly display nested arrays in Vue JS. Below is a snippet of my JSON data: { "id": 1, "slug": "test-page", "banner": { "title": "banner title", "subTitle": "my sub title", "hasSubTitle": false, "hasClass": " ...

Identifying the opening of a folder or file in an electron/node application

Is there a way to retrieve the name of a folder or file when they are opened? I have tried using fs.watch event, but it only seems to work when renaming, adding, or removing files/folders within the specified directory. For instance: //This code only de ...

I prefer to disable the toggle feature if the target remains unchanged

My goal is to create a step-by-step ordering system using the data-id="x" attribute to determine which content should be visible when selected. I want to make sure that if two elements have the same data-id, clicking on one will deselect the other. Any su ...

Converting an rrule date value from an array to a customized string format

Here is an array that I am working with: [{ evening_feeding: false evening_feeding_time: "19:00" feeding_frequency_rule: **"FREQ=DAILY;INTERVAL=2"** id: 890 morning_feeding: true morning_feeding_time: "04:00 ...

Steps for converting an image byte array into a bitmap after making changes to the byte array

I've been working on implementing Steganography in Android, focusing on coding the image bit by bit. private Bitmap add_text(Bitmap image, String text) { //converting image, message, and message length to byte arrays byte img[] = get_byte_da ...

Issue with material-ui-dropzone, the DropzoneAreaBase component not displaying the preview of the uploaded files

Has anyone encountered issues with the DropzoneAreaBase component from the material-ui-dropzone library? I am having trouble getting it to display added file previews. Any insights into why this might be happening? <DropzoneAreaBase onAdd={(fileObjs) ...

Guide to correcting Form Data errors with XHR resulting in a 400 Bad Request

This is a straightforward piece of code I've written. It's simply a POST request to my API endpoint using FormData. Interestingly, the API is returning a bad request error for reasons unknown to me. When I tested the API with curl, everything wo ...

Creating a thumbnail with a close button using an image

My code is available at the following link: https://codepen.io/manuchadha/pen/PBKYBJ In this form I have created, I am trying to implement an image upload feature using a file input. The goal is to display a thumbnail of the selected image below the file ...

What is the best way to update the content of a particular div and its associated link ID whenever the link is clicked?

I need to update the content of a div by clicking on an href link that includes an id named data. The issue I'm facing is that I can't access the id value within my script because it's passed within a function. How can I pass the data variab ...

Steps for retrieving user timezone offset and transmitting it to the server in an ASP.net application

I need assistance with capturing and sending a user's timezone or offset when they successfully sign in. I came across the "getTimezoneOffset" method in JavaScript, but I'm unsure how to automatically send this data without the user explicitly in ...

Make sure that the iframe loads the next page with enough force to break out

My dilemma involves an iframe that loads the new tab page. When a user clicks on the thumbnail, it opens within the iframe. My goal is to have any subsequent load in the iframe redirected to window.top. Is there a way to achieve this without manually setti ...

Tips on creating an inline editable cell in a Tree View

I've been working on a category tree that includes expand and collapse buttons. You can see what I have so far here: Category Tree Now, I'm looking to make each item inline editable. Can someone guide me on how to achieve this? If you want to t ...

What is the best method for directing to various pages on a GitHub Pages website?

My GitHub Pages site is live at this link. While the splash page loads perfectly, clicking on the circle to transition to the next page, 'landing.html', leads to a 404 error. I have exhausted all possible solutions to address this issue, includin ...

Having difficulty retrieving the Area and Range information in ChartJS

I am new to working with HTML5 and ChartJS. I have noticed two different types of declarations when attaching JS Chart Versions 1.0.1 and 2.1.1. Can you please provide some insight into this? Additionally, I am facing an issue where the stripes behind the ...