Arranging objects in an array according to a predetermined criteria

Presented below is an array:

        [{"cod_nivel":"INC2","cod_modelo":"D"},   
        {"cod_nivel":"PRIM1","cod_modelo":"B"},   
        {"cod_nivel":"INC2","cod_modelo":"B"},  
        {"cod_nivel":"INC1","cod_modelo":"D"},
        {"cod_nivel":"PRIM1","cod_modelo":"D"},
        {"cod_nivel":"BAC2","cod_modelo":"B"},    
        {"cod_nivel":"BAC2","cod_modelo":"D"},    
        {"cod_nivel":"BAC2","cod_modelo":"A"}]

The objective is to sort this array of objects by "cod_modelo" in ascending order, grouped by "cod_nivel". The desired result should be as follows:

    [{"cod_nivel":"INC1","cod_modelo":"D"},    
    {"cod_nivel":"INC2","cod_modelo":"B"},
    {"cod_nivel":"INC2","cod_modelo":"D"},    
    {"cod_nivel":"PRIM1","cod_modelo":"B"},    
    {"cod_nivel":"PRIM1","cod_modelo":"D"},
    {"cod_nivel":"BAC2","cod_modelo":"A"},    
    {"cod_nivel":"BAC2","cod_modelo":"B"},    
    {"cod_nivel":"BAC2","cod_modelo":"D"}]

A code was created for ordering the array first by cod_nivel and then by cod_modelo:

var sortedArray = array.sort(function (a, b) {
    return (a["cod_nivel"] > b["cod_nivel"]) ? 1 : -1;
}).sort(function (a, b) {
    if (a["cod_nivel"] == b["cod_nivel"])
        return (a["cod_modelo"] > b["cod_modelo"]) ? 1 : -1;
    else
        return 0;
});

However, it was noted that the current code also orders by "cod_nivel," resulting in the following array:

    [{"cod_nivel":"BAC2","cod_modelo":"A"},    
    {"cod_nivel":"BAC2","cod_modelo":"B"},    
    {"cod_nivel":"BAC2","cod_modelo":"D"},
    {"cod_nivel":"INC1","cod_modelo":"D"},    
    {"cod_nivel":"INC2","cod_modelo":"B"},
    {"cod_nivel":"INC2","cod_modelo":"D"},    
    {"cod_nivel":"PRIM1","cod_modelo":"B"},    
    {"cod_nivel":"PRIM1","cod_modelo":"D"}]

To achieve the desired order, a fixed sequence of "cod_nivel" needs to be defined:

  1. INC1
  2. INC2
  3. PRIM1
  4. PRIM2
  5. BAC1
  6. BAC2

A solution involves creating an array with the specified order of "cod_nivel" and utilizing it during sorting, like so:

var order_arr = ['INC1', 'INC2', 'PRIM1', 'PRIM2', 'BAC1', 'BAC2']

Subsequently, the array can be sorted first by cod_nivel based on the given sequence, followed by grouping by cod_modelo within each cod_nivel.

If further clarification is required, feel free to ask for assistance.

Answer №1

To organize an associative array with indexes, follow this example:

var level_code_order = {
    'INC1': 0,
    'INC2': 1,
    'PRIM1': 2,
    'PRIM2': 3,
    'BAC1': 4,
    'BAC2': 5
};

You can then proceed to sort the array using this method:

function compare(a, b) {
    if (a === b) {
        return 0;
    }
    return a < b ? -1 : 1;
}

var sortedArray = array.sort(function (a, b) {

    // Comparing values based on `level_code` from `level_code_order`
    var index_comparison = compare(level_code_order[a.level_code],
        level_code_order[b.level_code]);

    // If they are equal
    if (index_comparison === 0) {

        // Compare `model_code` values next
        return compare(a.model_code, b.model_code);
    }

    return index_comparison;
});

The resulting sorted array will look like this:

[ { level_code: 'INC1', model_code: 'D' },
  { level_code: 'INC2', model_code: 'B' },
  { level_code: 'INC2', model_code: 'D' },
  { level_code: 'PRIM1', model_code: 'B' },
  { level_code: 'PRIM1', model_code: 'D' },
  { level_code: 'BAC2', model_code: 'A' },
  { level_code: 'BAC2', model_code: 'B' },
  { level_code: 'BAC2', model_code: 'D' } ]

Answer №2

let info = [{
    "level_code": "INC2",
    "model_code": "B"
}, {
    "level_code": "INC2",
    "model_code": "D"
}, {
    "level_code": "INC2",
    "model_code": "B"
}, {
    "level_code": "PRIM1",
    "model_code": "B"
}, {
    "level_code": "INC2",
    "model_code": "B"
}, {
    "level_code": "INC1",
    "model_code": "D"
}, {
    "level_code": "INC2",
    "model_code": "B"
}, {
    "level_code": "PRIM2",
    "model_code": "D"
}, {
    "level_code": "BAC2",
    "model_code": "B"
}, {
    "level_code": "BAC2",
    "model_code": "D"
}, {
    "level_code": "BAC2",
    "model_code": "A"
}];
let orderArr = ['INC1', 'INC2', 'PRIM1', 'PRIM2', 'BAC1', 'BAC2'];
info.sort(function (x, y) {
    let diff = orderArr.indexOf(x.level_code) - orderArr.indexOf(y.level_code);
    if (diff === 0) {
        return x.model_code === y.model_code ? 0 : (x.model_code < y.model_code ? -1 : 1);
    }
    return diff;
});

After considering feedback, this updated version ensures safe number and string comparisons for precise sorting.

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

Is there a way for app.use to identify and match requests that begin with the same path?

Given that app.use() responds to any path that starts with /, why does the request localhost:3000/foo match the second method instead of the first? app.use("/",express.static('public'), function(req,res,next) { console.log(& ...

What could be the reason for my function throwing a TypeError with the message "<function> is not a function"?

Every time I try to call a function that clearly appears to be defined as a function, I continuously receive the error message: TypeError: [function name] is not a function. To demonstrate the issue, here is a simple example: main.ts import someFunction ...

Personalize your material-ui popover

Seeking assistance in customizing the shape of a material-ui popover similar to the one depicted in the image. https://i.sstatic.net/l5uNL.png I have created a working demo of the popover using React and provided a link for editing purposes. Any help? =& ...

Using both PHP and jQuery to add a class upon changing the URL

I am struggling to implement sorting functionality on my webpage, as the active class is not being added to the selected sorting option... Check out my code snippet below: <ul class="nav nav-tabs"> <li class="menusel active" name="hlavni" on ...

Experience a magical Vue form wizard just like Wilio

Searching for a vuejs wizard form similar to the Wilio Wizard Form. Tried out the Binar Code Wizard Form, but it's not quite what I'm looking for. Need a form wizard with a simple progress bar and step numbers like Wilio. Is it possible to mod ...

Divide a column containing dictionaries into individual columns using pandas

I have data stored in a postgreSQL database. Using Python2.7, I am retrieving this data and converting it into a Pandas DataFrame. However, the last column of this dataframe contains dictionaries of values. The DataFrame df is structured as follows: Statio ...

Setting up a connection between an Express server and a Mongoose database in

As someone who is relatively new to the express framework and mongoose database, I have mainly worked with relational databases in the past. I am attempting to create a database using the script below. Currently, mongod.exe is running and listening on loca ...

Unable to set a value of type 'String?' to a variable of type 'String?.Type'

Having trouble resolving this error: Here is the code snippet causing it: func setInfo(json: JSON) { self.name = json["name"].string self.email = json["email"].string let image = json["picture"].dictionary let imageData = image?["data"]? ...

Typescript is failing to compile classes in a reliable sequential order

In my MVC 5 project, I am using TypeScript and angular. There are three TS files: Controller1.ts, Controller2.ts, and app.ts. The issue arises when I compile the program for the first time - everything usually compiles correctly in the expected order. Howe ...

Using Vue components in NativeScript-Vue popups: A comprehensive guide

To initiate the popup, I include the following code in a root component: import parentt from "./parentt.vue"; . . . this.$showModal(parentt, { fullscreen: true, }); The contents of parentt.vue are as follows: <template> <StackLayout> ...

Managing arrays within nested structures

I am currently working on creating an array of structures with an array inside. However, I am facing an issue where only the first elements of both arrays are getting initialized with values. Can someone please provide assistance with this problem? #inc ...

Retrieve information from a LINQ query and convert it to JSON format

How can I retrieve data from LINQ in Json format? I tried this code snippet but it doesn't work public ActionResult GenerateShop() { LinqDataContext context = new LinqDataContext(); IEnumerable<shops> shops = context.s ...

Error log notification stating that there is an undefined constant while iterating through a PHP array

I'm dealing with a PHP array called $data that is structured like this... Array ( [section] => Array ( [345dfg] => Array ( [test] => Array ( ...

Regex can present two potential scenarios

I need to extract numbers from two different cases of a string. The first case is <@&!302050872383242240> And the second case is <@&302050872383242240> Is there a way to extract only the numbers from this string or remove the elemen ...

Having trouble retrieving the $_SESSION variable accurately from AngularJS

I am working with angularjs and need to retrieve a php session variable. I have created a php file named session.php with the following content: $_SESSION['phone'] = '55551864'; return json_encode($_SESSION['phone']); In my ...

`Zooming and scrolling feature within a masked image`

I'm struggling to achieve a scrolling zoom effect similar to the website mentioned below, but I can't seem to get it to fully zoom. Additionally, when I try to zoom in on a clipped shape or text while scrolling, the entire div ends up scrolling ...

The cgi.FieldStorage module now has the ability to retrieve JSON data from requests made using

My server is set up according to the guidance in Python Cookbook (ch.11). # server.py import cgi def notfound_404(environ, start_response): start_response('404 Not found', [('Content-type', 'text-plain')]) return [ ...

What is the best way to move information between two functions using jQuery?

When using the sortable jQuery, how can I pass variable data from one function to another? I have the following: start:function(event,ui){ var data="xyz";} and receive:function(event,ui){ } I am looking to retrieve the value of var data in the receive ...

I'm having trouble making a Javascript ajax request to my Web API controller page. It seems like I just can't figure out the correct URL

Currently, I am facing an issue with my registration page where I am attempting to save input fields into a new record in the Users table. <button class="btn-u" type="submit" onclick="submitclicked()">Register</button> The click event trigger ...

Verify that the elements in the input array are numerical values

My current challenge in PHP involves checking if the input variables are numbers within an array, where each number is separated by a space within a form. Unfortunately, using is_int and is_numeric is not effective in this case because the input is treate ...