Rearrange object based on several criteria - JavaScript

var numbers = {
  "value": [{
      "num1": 1,
      "num2": 10
    },
    {
      "num1": 15,
      "num2": 13
    },
    {
      "num1": 26,
      "num2": 24
    },
    {
      "num1": 6,
      "num2": 25
    },
    {
      "num1": 15,
      "num2": 20
    }
  ]
};

var sortedNumbers = numbers.value.sort(function(x, y) {
  return x['num2'] < y['num2'] ? 1 : -1;
});

console.log(sortedNumbers);

The result after the initial sorting should be further sorted as follows:

[
    {
        "num1": 6,
        "num2": 25
    },
    {
        "num1": 15,
        "num2": 20
    },
    {
        "num1": 1,
        "num2": 10
    }
    {
        "num1": 26,
        "num2": 24
    },
    {
        "num1": 15,
        "num2": 13
    }
]

Therefore, the sorting order should be based on the highest value of "num2" first and then in descending order as long as "num2" is greater than "num1". I have tried various methods without success; any assistance would be greatly appreciated.

Thank you for your help!

Answer №1

To organize the data, you can first compare the values of countB and countA. Afterwards, sort them based on the value of countB.

const
    info = [{ CountA: 1, CountB: 10 }, { CountA: 15, CountB: 13 }, { CountA: 26, CountB: 24 }, { CountA: 6, CountB: 25 }, { CountA: 15, CountB: 20 }];

info.sort((item1, item2) =>
    (item2.CountB > item2.CountA) - (item1.CountB > item1.CountA) ||
    item2.CountB - item1.CountB
);

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

Answer №2

To start off, the array values can be extracted when the condition

"countb" >= "countA"
is met. This extracted portion of the array should then be sorted, followed by adding the remaining values at the end (while ensuring that the order is maintained for cases where
"countb" < "countA"
):

var data = {
  "input": [{
      "countA": 1,
      "countB": 10
    },
    {
      "countA": 15,
      "countB": 13
    },
    {
      "countA": 26,
      "countB": 24
    },
    {
      "countA": 6,
      "countB": 25
    },
    {
      "countA": 15,
      "countB": 20
    }
  ]
};

const ElementsToSort = data.input.filter(elem => elem.countA <= elem.countB);
const RemainingElements = data.input.filter(elem => ElementsToSort.indexOf(elem) < 0);

// sort as you did previously
const PartiallySorted = ElementsToSort.sort(function(a, b) {
  return a['countB'] < b['countB']
          ? 1
          : a['countB'] > b['countB']
            ? -1
            : 0;
});

// add the remaining values to the partially sorted array
const sorted = PartiallySorted.concat(RemainingElements);
console.log(sorted);

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

Tips for closing process.stdin.on and then reopening it later

I've been facing a challenge with an exercise. In this exercise, the client will input a specific integer x, followed by x other y values separated by spaces. The output should be the sum of each y value, also separated by spaces. For example: Input: ...

Is there a way to programmatically fetch files from a MySql / Node.js server?

I've been working on my CRUD app and I'm currently focusing on downloading files from a MySql Nodejs server. Here are the steps I have accomplished so far: I created a function in userContoller.js to query the MySql database for the id=179 (just ...

Unable to access a nested JSON object that has a repeated name

I'm relatively new to working with JSON, so the issue I'm facing may be simple, but I haven't been able to find a similar problem on stackoverflow. Here's my question: My goal is to access a nested JSON object like: pizza.topping.ratin ...

How can I insert a item into an Array using JavaScript code?

My instructor set up an array in my JavaScript file that is off limits for me to modify. My task is to add new objects to it through code without directly manipulating the existing array. Here's a snapshot of what my array contains: const words = [{ ...

Inconsistency with Mobile Viewport Problem

Apologies for the chaos below, but I've spent quite some time attempting to fix this on my own. It's time to surrender and seek assistance! Here are some screenshots to illustrate the issue: The problem is that sometimes the webpage functions c ...

Having trouble inserting an image using Vue?

I am having trouble understanding why only the first image loads, while the others do not. 1. <img :src="require('../assets/batatas.jpg')" :alt="item.title" /> 2. <img :src="'../assets/batatas.jpg'" ...

Issue with Observable binding, not receiving all child property values in View

When viewing my knockout bound view, I noticed that not all values are being displayed. Here is the script file I am using: var ViewModel = function () { var self = this; self.games = ko.observableArray(); self.error = ko.observable(); se ...

Encountered a CastError in Mongoose when trying to cast the value "Object" to a string

I am struggling with a Mongoose CastError issue within my Node.js API. The problem arises at a specific route where data is being returned appended with some additional information. Despite finding various solutions for similar problems, my scenario seems ...

Loop through the JSON data to generate clickable links in the innerHTML

I've been searching through various resources for a solution to the issue I'm facing. My goal is to iterate through a JSON object and extract all the ids and corresponding dates from each top_worst section. The structure of the JSON data is as fo ...

When refreshing, the useEffect async function will not execute

Upon page load, the getImages function is intended to run only once. After refreshing the page, both tempQuestionImages and questionImages are empty. However, everything works perfectly after a hot reload. I am utilizing nextJs along with Firebase Cloud ...

In JavaScript, the clearTimeout function may not always return a

Could someone please help me troubleshoot the issue in my code snippet below? I am trying to declare a public variable and assign it to a setTimeout function. If the variable is not null, I want to clear the timeout before setting it again. However, when ...

Ensure at least one checkbox is selected by using jQuery validation

I wrote the code below to select multiple checkboxes and validate that at least one checkbox is selected. The data submission to the database works if I remove onsubmit="return validate_form()". However, I want to ensure that at least one checkbox is selec ...

Asynchronous Middleware in ExpressJS Routing

I'm having trouble implementing a middleware in Express. Whenever I make a request, I end up with infinite loading times. I've searched on various platforms but couldn't find any examples that utilize an async await middleware stored in a se ...

Modify the URL query to read as "favicon.ico"

Whenever I make a GET request to my node.js/express web server with a URL following the route, instead of storing that URL, the server ends up saving favicon.ico: var express = require("express"); var app = express(); app.get("/:query", function (req, re ...

Utilize Dinero.js to implement currency formatting for input fields in React applications

I am currently working on a form in React that requires certain input fields to be formatted as money currency. These inputs should be prefixed with the dollar sign ($), include commas for thousands separation, and have exactly two decimal points. During ...

The @Input() function is failing to display or fetch the latest value that was passed

I am currently working on an angular project, and I've encountered a situation where I'm attempting to send a value from a parent component to a child component using the @Input() decorator. Despite my efforts, the child component continues to di ...

Merging two arrays of objects from the same response in JavaScript

How can I efficiently merge two arrays of objects from the same response? let data = [{ "testLevel":"mid", "testId":"m-001", "majorCourse": [ { "courseName":"C++" ...

Animation is not applied to Bootstrap Collapse on a row within a table

My Bootstrap 4 table has an issue - when I apply the "collapse" class to a table row, it behaves differently compared to applying it to a div element. Clicking "animate div" smoothly animates the target div, but clicking "animate tr" does not animate the ...

Can you explain the significance of the regular expression in a dojo configuration file named dj

As I was working on developing dojo application modules, I came across a regular expression in tutorials. var pathRegex = new RegExp(/\/[^\/]+$/); var locationPath = location.pathname.replace(pathRegex, ''); var dojoConfig = { asyn ...

Having trouble with jQuery show/hide not functioning properly?

My website has a sub-menu section with a shopping cart icon. When a user hovers over the icon, it reveals a hidden cart section. The user can then move the mouse into the cart section to remove items. The problem I'm facing is that if a user displays ...