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

The Ajax function is unable to accept JSON data as input

I am trying to figure out why I am unable to access data from a JSON object (json.projects[i].projName) when calling it from within an AJAX function. Below is the code that demonstrates this issue: var json = JSON.parse(data); for (var i = 0; i < json ...

Populate the table with JSON content using jQuery

I am attempting to populate a table with JSON data using jQuery, but the content within the div remains empty. I need assistance in identifying the error. The array list contains the data (I verified this using console.log(list)). Additionally, list[' ...

The error message "TypeError: addNewUser is not a function in React.js onSubmit

What could be causing the error message "TypeError: addNewUser is not a function"? The issue arises when I complete the form and click save, displaying the error that addNewUser is not defined as a function. The problem occurs within the following code ...

Exploring Amcharts using detailed JSON data

[{"SUM_PTS":{"datatype":"INTEGER","length":"8","value":"29903727","obfuscated":"false"},"SUM_TOTAL":{"datatype":"INTEGER","length":"10","value":"1644704985","obfuscated":"false"},"MID":{"datatype":"ALPHANUMERIC","length":"27","value":"Vendor 1","obfuscated ...

Is there a way to retrieve a comprehensive list of all anchors that contain the data-ng-click attribute

I am currently working on a web application built with asp.net and angularjs. My goal is to specifically retrieve all anchor tags that have the attribute data-ng-click assigned to them. Is there a way to achieve this? If so, how can it be done? I a ...

There seems to be an issue with Jquery not triggering the Webservice method in the Firefox browser, despite it working successfully in Chrome

Currently, I have an issue where a webservice method called via ajax in jQuery is functioning correctly in Chrome and IE browsers but not in Firefox. Here is the jQuery code: $("#btnUpdate").click(function () { var objEmp = { employeeID: $("#Em ...

Having trouble loading environment variables in NextJS on Heroku?

I am currently utilizing NextJS and deploying my application on Heroku. When the page initially loads, I am able to retrieve data through getInitialProps without any issues. However, when trying to access this data in a regular function, I encounter an er ...

jQuery Plugin - iDisplayLength Feature

I am currently using DataTables version 1.10.10 and I am looking to customize the main plugin Javascript in order to change the iDisplayLength value to -1. This adjustment will result in displaying "All" by default on all data tables, allowing users to fil ...

Unforeseen SyntaxError: Unexpected symbol detected

Encountering an issue while attempting to send raw data as parameters in express. Specifically, there is an error occurring at the 'fields' variable... function getWithQuery(req,res){ console.log(req.params); var query = {name: new RegEx ...

Is it advisable to hold off until the document.onload event occurs?

I'm working with a basic HTML file where I need to generate SVGs based on data retrieved through an AJAX call. Do I need to ensure the document is fully loaded by enclosing my code within a document.onload = function() { ... } block, or can I assume ...

How can we create external labels for a polar chart in ng2-charts and chart.js, with a set position outside the circular rings?

Currently, I am working on creating a polar chart using Angular along with chart.js version 2.8.0 and ng2-charts version 2.3.0. In my implementation, I have utilized the chartjs-plugin-datalabels to show labels within the polar chart rings. However, this p ...

Accessing variables in AngularJS from one function to another function

I am facing an issue where I need to access a variable in one function from another function. My code structure is as follows: NOTE: The value for submitData.alcohol is obtained from elsewhere in my code. angular.module('app',['ui.router&a ...

Automatically Populate list upon webpage initialization - React, Redux, Firebase

A webpage I am working on consists of two main components: Categories and Items By utilizing the function initCategories() called within the componentDidMount() lifecycle method of Categories, I successfully display all categories on the screen. The initC ...

Implementation of Gallows Game

SITUATION Recently, I took on the challenge of creating a "HANGMAN" game using JavaScript and HTML exclusively for client-side machines. The logical part of the implementation is complete, but I am facing a hurdle when it comes to enhancing the aesthetics ...

What could be causing my directive to not display my scope?

I am currently developing a directive that includes a custom controller, and I am testing the scope functionality. However, I am facing an issue where the ng-show directive is not functioning as expected when trying to test if the directive has a scope fro ...

Updating components in Angular4 when route changesHow to update components on route

How can I ensure my component updates when the route changes? Here is the code for my component : import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { ListService } from '.. ...

How to retrieve the third party child component within a Vue parent component

Within my example-component, I have integrated a third-party media upload child component called media-uploader: <example-component> <form :action= "something"> // Other input types <media-upload :ref="'cover_up ...

Numerous applications of a singular shop within a single webpage

I have a store that uses a fetch function to retrieve graph data from my server using the asyncAction method provided by mobx-utils. The code for the store looks like this: class GraphStore { @observable public loading: boolean; @observable ...

Tips for aligning and emphasizing HTML content with audio stimuli

I am looking to add a unique feature where the text highlights as audio plays on a website. Similar to what we see on television, I would like the text to continue highlighting as the audio progresses. Could someone please provide me with guidance on how ...

What is the best way to incorporate a unique font with special effects on a website?

Is there a way to achieve an Outer Glow effect for a non-standard font like Titillium on a website, even if not everyone has the font installed on their computer? I'm open to using Javascript (including jQuery) and CSS3 to achieve this effect. Any sug ...