Arrange JSON objects within an array based on the values of three specific fields

Within an array, I am working with the following structure:

[
    {
        "playerName": "Stack",
        "leaguePoints": 100,
        "wins": 280,
        "miniSeries": {
            "progress": "WNN",
            "losses": 0,
            "wins": 1
        }
    },
    {
        "playerName": "Overflow",
        "leaguePoints": 90,
        "wins": 280
    }
    {
        "playerName": "StackOverflow",
        "leaguePoints": 0,
        "wins": 100
    }
]

To sort the array elements properly, follow these guidelines:

If leaguePoints = 100, sort by (miniSeries.wins + miniSeries.losses) or number of Ns left in miniSeries.progress

If leaguePoints is less than 100, sort by leaguePoints

If leaguePoints equals 0, sort by wins

I've tried using Ege Özcan's multiple parameters sort, which works for leaguePoints and wins, but not for miniSeries.

The desired outcome should resemble this:

Name    leaguePoints    Wins    MiniSeries
Stack   100             10      LWN
Stack   100             25      WNN
Stack   100             5       NNN
Stack   99              50      ---
Stack   70              250     ---
Stack   0               300     ---
Stack   0               200     ---
Stack   0               100     ---

Answer №1

Perhaps what you are seeking is

function sortByProgress(a, b) {
    // Compare number of "N"s in each value
    return b.split("N").length - a.split("N").length;
}
function sortByMiniSeries(a, b) {
    // Sort by total games played
    return a.wins + a.losses - (b.wins + b.losses) || sortByProgress(a.progress, b.progress);
}
function sortByRank(a, b) {
    // Arrange by league standings
    return a.leaguePoints - b.leaguePoints || (a.leaguePoints == 0
      ? a.wins - b.wins
      : (a.leaguePoints == 100 
        ? sortByMiniSeries(a.miniSeries, b.miniSeries)
        : 0 ) );
}
playerArray.sort(sortByRank);

The || operator uses short-circuit evaluation, where the right operand is returned if the left one is falsy (in this case: 0, indicating equal values).

Answer №2

It would be beneficial to implement a 2 pass processing method.
Firstly, separate the data into 3 distinct groups: leaguePoints100, leaguePoints0, and the remaining data.

You are capable of sorting each group individually, then utilize Array.concat() to combine the three sorted arrays, view an example here.

Lo-Dash can simplify the tasks, beginning with groupBy() on leaguePoints:

groups = _.groupBy(data, function(item) {
  switch (item.leaguePoints) {
    case 100:
        return 'leaguePoints100';
    case 0:
        return 'leaguePoints0';
    default:
        return 'other';
  }
);

Following that, apply sortBy() on the three groups:

groups['leaguePoints100'] = _.sortBy(group['leaguePoints100'], sortLeaguePoints100);
groups['leaguePoints0'] = _.sortBy(group['leaguePoints0'], 'wins');
groups['other'] = _.sortBy(group['other'], 'leaguePoints');

This approach enhances the readability of the code, although it may seem somewhat repetitive.
KISS, my friend.

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

Creating a JSON Response Using PHP API

I created a basic JSON response to test the functionality of an AJAX request on a mobile device. Using a local domain called test.local, I generated a json response. header("Content-Type:application/json; charset=utf-8"); echo json_encode(array('nam ...

Develop a scrambled PHP webpage for a CAPTCHA system

I've implemented the cool-captcha feature in my registration form. Here's the code snippet that generates the Captcha image: <img src="captcha.php" id="captcha" /> However, there is an issue where anyone can easily access the "captcha.ph ...

The select dropdown does not automatically refresh when the array value changes

I am facing an issue with a select dropdown that is populated by an array filled with data from the server response: myApp.controller('mController', function($scope, $routeParams, $http, contextRoot) { var dataObject = {} $scope.arr = [ ...

What could be causing a momentary 404 error when I click on a next.js `Link` that connects to an API endpoint before redirecting to the intended page?

Hello there, I recently followed a tutorial on adding authentication with Passport to Next.js from this resource: https://auth0.com/blog/next-js-authentication-tutorial/ However, I encountered a minor issue. When I click the "/login" Link in my Next.js ...

Differences between x-www-form-urlencoded and JSON in HTTP POST requestsWhen

Struggling to make a decision, I am currently using php lib curl to send data as x-www-form-urlencoded with the following code: curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($this->arguments)); or curl_setopt($curl, CURLOPT_POSTFIELDS, $t ...

Creating dynamic dropdown menus within a Rails 3 form using Prototype and incorporating database queries

Recently, I've been on the hunt for a seamless method to create dynamic dropdown menus within a form that can be populated with data from a database based on the selection of a previous dropdown. Unfortunately, my search for a suitable Rails 3/prototy ...

Variety of properties determined by a "type" prop, expanding variations based on a value from the interface

I am trying to enhance a type based on a value from the main interface. If the type == multiline, it will have a specific interface, and if the type == icon, it will have a different type. import React, { memo, useCallback, ReactNode } from 'react&apo ...

Save information from an HTTP request made with a manually entered URL

As I delve into the world of web development, a particular issue has me stuck. My current project involves implementing a user password reset feature. The process goes like this: the user receives an email with a URL containing a unique token, clicks on th ...

How can I use Ajax to show only one div on the entire page while keeping the CSS and other header content intact

One of my clients is looking to integrate a merch shop into their website. The existing merch page is not visually appealing and doesn't match the aesthetic of the client's site. I am considering using AJAX GET to fetch the content of the merch p ...

Python script for converting log.txt file to JSON

Currently in the process of learning Python with a limited programming background, I have taken on a challenging project. The task at hand involves converting a system log stored in a .txt file into JSON format. The ultimate goal is to create a Python pro ...

`Establish a hierarchical structure by incorporating a new value across multiple arrays`

Is anyone able to assist with a syntax issue I am facing? I need help figuring out how to add the 'doc' value to the 'attach' array at the same level as 'pdf' and 'pptx'. Any guidance is appreciated! <?php $body = ...

What is the most efficient way to prevent duplicate items from being added to an array in a Vue 3 shopping cart

I currently have a functional shopping cart system, but I am facing an issue where it creates duplicates in the cart instead of incrementing the quantity. How can I modify it to only increment the item if it already exists in the cart? Also, I would like t ...

Retaining user interactions through cookies

Currently developing a notification for users on the homepage regarding the use of cookies on this site. I aim to provide an option for users to dismiss the message, with the browser remembering their choice so it does not reappear upon reloading the page ...

Retrieving the final element from a TypeScript JSON array

I am trying to retrieve the value of the "id" property from the last element in an array of JSON objects. While I can easily find each element by id, I specifically need to extract the value of the last "id" in the array of JSON objects. In the example p ...

Access another key within an object

Here's a code snippet from my module: exports.yeah = { hallo: { shine: "was", yum: this.hallo.shine } } In the above code, I'm attempting to reference the shine property in yum: this.hallo.shine However, when I run the script, ...

Exploring Javascript: Understanding the Contrast Between Function and Class

In June 2015, with the introduction of ECMAScript 6, a new syntax for Javascript classes was unveiled. The new syntax is exemplified by the following code snippet: class Polygon { constructor(width, height) { this.width = width; thi ...

Reverse a filter within an ng-repeat loop - AngularJS

I have a question that I haven't found the answer to yet. Here is the issue I'm facing: The JSON data I am working with has this structure: [{ "batch_queue_name": "Batch One", "start_date": "12/01/2016 10:18 P.M.", "end_date": "12/03/2016 ...

Change the navbar brand in Bootstrap to be hidden on small screens like mobile devices

I am facing an issue with the navbar on my website where it expands in height when viewed on mobile devices due to not fitting into a single line. I have observed that if I remove the brand, it fits perfectly. However, I want to keep the brand visible on l ...

Struggling with integrating JSON data into JqGrid

I've encountered a challenge with binding my Json data to a JqGrid. Within my Default.aspx.cs file, I have the following method: [WebMethod] public static string GetData() { CustomerHelper C = new CustomerHelper(); ...

Guide on incorporating Bootstrap JS into HTML5 reusable web elements

RESOLVED: the solution is in a comment TL;DR: Issues triggering Bootstrap's JS, likely due to incorrect import of JS scripts I've been working on integrating Bootstrap with my custom reusable web components across all pages. Specifically, I&apo ...