Rearrange items based on multiple criteria - initial sorting by an additional array followed by sorting by a different property within

I have an array of objects that I need to sort in a specific manner. First, I want items with the code 'c' to come first, followed by 'y', and then 's'. Within each group (c, y, s), they should be sorted based on the counter values. For example, for code 'c', it should be sorted by the counter i.e. c- counter 1, c- counter 2.

var data = [ 
    { age:7, counter: 1, code: 'c'},
    { age:5, counter: 2, code: 'c'},
    { age:4, counter: 3, code: 'c'},
    { age:19, counter: 2, code: 'y'},
    { age:22, counter: 1, code: 'y'},
    { age:57, counter: 1, code: 's'},
    { age:80, counter: 2, code: 's'}
]

After searching on SO, I was able to sort by 'c', 'y', 's' using the following code snippet. However, I'm stuck at sorting by the 'counter' values within each category. Can anyone help me achieve this nested sorting?

var order = ['c','y','s'];
data.sort(function(a,b){
    return order.indexOf(a.code) < order.indexOf(b.code) ? -1 : 1;
})

Answer №1

To organize the data based on the code, you can utilize an object and then arrange it by count.

var items = [{ name: 'apple', quantity: 1, code: 'a' }, { name: 'banana', quantity: 4, code: 'b' }, { name: 'orange', quantity: 3, code: 'o' }, { name: 'kiwi', quantity: 2, code: 'k' }];

items.sort(function (x, y) {
    var order = { a: 1, b: 2, o: 3, k: 4 };
    return order[x.code] - order[y.code] || x.quantity - y.quantity;
});

console.log(items);

Answer №2

To ensure correct functionality, make sure to define the array as:

var sequence = ['b', 'z', 'm'];

If 'b', 'z' and 'm' are not constants, they should be declared as variables.

In addition, it is important to compare the counter variables when codes are identical:

data.sort(function(x,y){
   if ( x.code == y.code )
   {
        return x.counter - y.counter;
   }
   else
   {
       return sequence.indexOf(x.code) - sequence.indexOf(y.code);
   }
})

Answer №3

Here's a neat method for organizing data based on a counter:

var sequence = [ 'c', 'y', 's' ];

data.sort(function (first, second) {
    var result;

    if (sequence.indexOf(first.code) === sequence.indexOf(second.code))
    {
        result = first.counter - second.counter;
    } else {
        result = sequence.indexOf(first.code) - sequence.indexOf(second.code);
    }

    return result;
});

Answer №4

This method provides a dynamic way to compare conditions one after another.

var data = [{ age: 7, counter: 1, code: 'c' }, { age: 5, counter: 2, code: 'c' }, { age: 4, counter: 3, code: 'c' }, { age: 19, counter: 2, code: 'y' }, { age: 22, counter: 1, code: 'y' }, { age: 57, counter: 1, code: 's' }, { age: 80, counter: 2, code: 's' }];

Array.prototype.orderBy = function(...expresions) {
  var arr = this;
  return this.sort((a, b) => {
    var result;
    expresions.every(ex => (result = ex(a) - ex(b)) === 0)
    return result;
  });
}

var codeOrder = {
  c: 1,
  y: 2,
  s: 3
};
var result = data
  .orderBy(i => codeOrder[i.code], i => i.counter)
console.log(result);

Operation Details

Here's how it functions:

dataArray.sortBy(ex1[, ex2[, ex3]])

Each argument in this method is a function that takes an item from dataArray as input and returns a number corresponding to that item. If any expressions yield the same value for adjacent items, evaluation continues with the next expression until they produce different results or there are no more expressions left to test.

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

Retrieve information from a deep array structure

How can I extract the `id` from each marker's `routes` array in this JavaScript object while still referencing `item.id`? { "markers": [ { "id": "77475", "smsCode": "77475", "name": "Abbey Sports Centre" ...

Searching for a specific bus stop within an array based on a designated route

There's an issue at hand. We have a route with several bus stops. We need to determine the next stop on this route. The "_stopNum": "1" indicates that the stop is the first one on the route. Take a look at a stop example: { "route": [ { ...

Verify if there are multiple elements sharing the same class and initiate a certain action

I am working with three products that have a similar structure: tickbox | label (same text but different value) | Qty dropdown (different input name) These products fall into three different label "classes": 1st - <label for="related-checkbox-708745 ...

Discovering the Newest Product Updates through API Integration

I have a component that displays only the most recent product fetched from an API: const about = ({products}) => { const data = products.attributes console.log(data) return ( <div> <h1>{data.Name}</h1> ...

Is there a way to export a single page in NextJS?

How can I create a build and export a specific page in NextJS? For example, I would like to have only one specific HTML page in the "out" directory as a result. ...

Using THREE Js to rotate a mesh on the Y-axis towards a targeted vector location

I've been trying all day to adjust the orientation of a mesh on its Y axis towards a specific location within another mesh. I've experimented with different methods, but none have yielded successful results so far. Here is the code I currently ...

I am repeatedly encountering the Firebase error message stating that a Firebase App named '[DEFAULT]' already exists due to a duplicate app (app/duplicate-app)

import React, { Component } from 'react' import './App.css'; import "bootstrap/dist/css/bootstrap.min.css"; import firebase from 'firebase/app'; import 'firebase/database'; import ThreadDisplay from &apos ...

Deploying a React App to Github Pages Results in a Blank Screen

After successfully uploading a simple react app onto GitHub pages using gh-pages, I attempted to import the Shards dashboard project (https://github.com/DesignRevision/shards-dashboard-react) onto my GitHub page. Unfortunately, all I see is a blank page. ...

CSS transition fails to revert

My standard opacity animation is not working in reverse order. Here is a link to the JSFiddle example. According to the documentation, it should work automatically. Since I am new to JavaScript, I am unsure if this issue lies in my code or if the CSS anima ...

Initiate and terminate server using supertest

I've developed a server class that looks like this: import express, { Request, Response } from 'express'; export default class Server { server: any; exp: any; constructor() { this.exp = express(); this.exp.get('/' ...

When the add button is clicked, I would like to implement a feature where a checkbox is added

When the user clicks on the link "출력하기", I want the web page to add a checkbox to all images. I wrote this code, but it's not working. Can anyone help me? This is my JS: $(document).ready(function(){ $("#print").on('click', fu ...

Transfer the value of a JavaScript variable to a PHP variable

var javascript_data = $("#ctl00").text(); <?php $php_variable = ?> document.write(javascript_data); <? ; ?> Is there a way to transfer the javascript_data into the php_variable? I'm encountering an issue with this code. Any suggestions? ...

Enhance the user experience by implementing a smooth transition effect when loading new pages

Recently, I've been exploring a method to load content from an external HTML file using AJAX on my website. While it's working well, I'm now interested in adding a page transition effect when the content changes. Specifically, I'd like ...

The value from the textbox is not being received by the JavaScript and PHP

I'm encountering an issue with my codes where they are not properly passing the value of the verification code from the textbox to JavaScript and then to PHP. I need assistance in resolving this issue. Below is the snippet of code: HTML: /* HTML c ...

Ways to retrieve the content from an element embedded within a hyperlink using Python

Looking for a simple script that can be used to input a URL and extract the text of a specific HTML element on the page. For instance, if I input the URL , I would like to retrieve the "Position" value, which is CB in this example, and display it on my pag ...

How can I showcase a variety of movie clips and keep them updated in real-time?

Looking for some help with an Array named combo. The goal is to populate it with movieclips based on user clicks - for example, if the user clicks "1," then add "1" to the Array and display it in a designated area. However, I'm stuck and unsure of ho ...

Information regarding Django and managing static files during deployment through pythonanywhere

Is there a way for me to run collectstatic again in PythonAnywhere? I ran it after removing a line from my remote repository, but the new styles don't seem to be applying. Any suggestions on what I can do? English is not my first language. ...

How to create a redirect on a webpage using HTML and JavaScript based on a specified date

I'm relatively new to coding and I am attempting to create a script in my index.html file that will redirect to another HTML file once a specific date and time have been reached. This is the code snippet I have so far: <!DOCTYPE html> <html ...

The value of the variable remains static within the axios then method

let isFound = false; axios .get(link) .then((response) => { response.data.map((element) => { if (element.id_ticket.toString() === nbTicket) isFound = true; }); console.log(isFound); }); What I'm attempting to ...

Show the contents of a JSON file using Vue

I have a JSON file containing some data that needs to be fetched and displayed in a component. In the actions of my Vuex store, I've implemented: async getTodos (context) { const todos = [] const response = await fetch('../../data/todos.jso ...