Ordering an array based on two integer properties using JavaScript

Here is an array of objects I am working with:

const items = [
    { name: "Different Item", amount: 100, matches: 2 },
    { name: "Different Item", amount: 100, matches: 2 },
    { name: "An Item", amount: 100, matches: 1 },
    { name: "Different Item", amount: 30, matches: 2 }
]

I have a requirement to sort these objects based on both the matches and amount properties. The expected result after sorting should be as follows:

[
    { name: "Different Item", amount: 100, matches: 2 },
    { name: "Different Item", amount: 100, matches: 2 },
    { name: "Different Item", amount: 30, matches: 2 },
    { name: "An Item", amount: 100, matches: 1 }
]

The primary sorting criteria is based on the matches property, followed by sorting based on the amount property within each group of identical matches. While I am aware that we can individually sort by either matches or amount, such as:

items.sort((a, b) => a.matches - b.matches);

I need guidance on how to perform sorting based on both properties simultaneously.

Answer №1

To sort objects based on criteria, you can utilize the `Array#sort` method. This will order the objects first by `matches` and then by `amount`.

const items = [
    { name: "Different Item", amount: 90, matches: 2 },
    { name: "Different Item", amount: 100, matches: 1 },
    { name: "An Item", amount: 80, matches: 1 },
    { name: "Different Item", amount: 30, matches: 2 },
    { name: "Different Item", amount: 40, matches: 1 },
    { name: "Different Item", amount: 50, matches: 1 },
    { name: "An Item", amount: 10, matches: 1 },
    { name: "Different Item", amount: 20, matches: 2 },
];

const sortedItems = [...items].sort((a, b) => b.matches - a.matches || b.amount - a.amount);

console.log(sortedItems);

Answer №2

To demonstrate sorting based on two criteria using Array#sort, an alternative approach could be:

const items = [
    { name: "Different Item", amount: 100, matches: 2 },
    { name: "Different Item", amount: 100, matches: 2 },
    { name: "An Item", amount: 100, matches: 1 },
    { name: "Different Item", amount: 30, matches: 2 }
]

const result = items.sort((a, b) => {
  
  const matches = b.matches - a.matches;
  
  // If a.matches and b.matches are not the same,
  // arrange this pair of a and b elements by
  // matches in descending order
  if(matches !== 0) {
    return matches;
  }
  
  // In cases where the a and b pair have equal matches value,
  // sort them based on secondary criterion; 
  // amount in descending order
  return b.amount - a.amount;
});

console.log(result);

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

Generate Material UI sidebar components that are positioned above all other components

I am currently working on a sidebar component using the Material UI Drawer component. I am looking to add components that align side by side with the sidebar, similar to the green box shown in the image below. https://i.sstatic.net/aAtn6.png After attem ...

The response of the Typescript Subscription function

I'm struggling with retrieving the subscribe array in NG2. Being new to typescript, I find it difficult to understand how to pass variables between functions and constructors. This is what my code currently looks like: export class RosterPage exten ...

Getting the value of a button using JavaScript

Is there a way to retrieve the value of a button when multiple buttons are generated dynamically? I have a JavaScript function that creates buttons in a list based on my search history, with each button labeled as a city name. However, after clicking on o ...

Verifying if a number is present in a textbox when inserting text (without using setTimeout)

I have an input field similar to the one shown below: <input type ="number" id="numberTxt" placeholder="Number Only"/> To ensure that the value entered is a number, I am using the following function with the keypress event: <script> ...

Creating routes in Node.js after setting up middleware

Currently tackling a project using node.js and encountering a specific issue. After setting up all routes with express (app.get("..", func)), I find myself stuck with a middleware that catches all requests and redirects to a 404-page. The problem arises w ...

Can you explain the distinction in JavaScript between declaring a variable with `var a = xyz[]` versus `var a = xyz

Can someone clarify the difference between the following statements in JavaScript (or jQuery)? var a = xyz[] var a = xyz{} I tried looking it up online, but couldn't find a definitive answer. If anyone knows the difference, please enlighten me. ...

Unselect all checkboxes except for the one that was clicked

In a project, I have 3 checkboxes that are interconnected and when one is clicked or checked, I want the others to be cleared while keeping the clicked checkbox checked. This behavior is similar to radio buttons but I cannot use radio buttons due to client ...

Problem encountered with the JavaScript for loop failing to execute consistently on each iteration

Currently, I am working on a JavaScript code that alerts the count in an array of pages. The variable urls represents an array of page names, while count contains the count value. My goal is to alert the count value for each page in the urls array. Howe ...

Ways to enhance the data for my YouTube video uploads version 3

Currently facing an issue where Google has restricted my daily queries to 10,000. I am in search of a solution to adjust my chunksize either up or down. Uncertain about the exact amount to increase or decrease to limit the number of queries per upload, her ...

"Access Denied: Error 403 - Forbidden" encountered during the CSS minification and bundling process in ASP.NET Web Forms

After migrating my ASP.NET web forms application from a managed VPS to AWS EC2 using AWS Elastic Beanstalk, I encountered an issue with CSS bundling and minification. While the JavaScript was successfully bundled and minified on the Amazon server, the CSS ...

Exploring the intricacies of mapping an Array of Arrays

I'm currently tackling a data manipulation project that involves iterating through an array of arrays and generating a single string containing all possible combinations found within these arrays. For instance: const array = [ [{id: 1}, {id: 2}], ...

What is the process for inserting text within a .data() method?

I have set up this AJAX request: $.ajax({ method: "GET", url: $('.item').data('query_selector'), dataType: "html" (The ajax call works perfectly, returning something like "item=Mann+Co.+Supply+Crate&quality=6&trad ...

I'm struggling to make this script replace the values within the table

I am struggling with a script that I want to use for replacing values in a google doc template with data from a google sheet. The script is able to recognize the variables and generate unique file names based on the information from the google sheet. Howev ...

Displaying a div upon hovering over another div is resulting in numerous server requests and a flickering effect

I am attempting to create a hover effect where one div floats next to another. The layout of the divs is like a grid, placed side by side. Check out my code on this fiddle. Using plain JavaScript, I want to display a second div (div2) floating next to div ...

Run a JavaScript function once the one before it has finished executing

I need help with executing a series of JavaScript functions in a specific order, where each function must wait for the previous one to complete. I've tried multiple approaches but haven't been successful so far. Any suggestions would be greatly a ...

Ensuring the accuracy of nested objects through class validator in combination with nestjs

I'm currently facing an issue with validating nested objects using class-validator and NestJS. I attempted to follow this thread, where I utilized the @Type decorator from class-transform but unfortunately, it did not work as expected. Here is my setu ...

Implement feature to enable selection using jQuery

I have a question about implementing an <option value="fiat">Fiat</option>"> element into a dropdown list using jQuery. I've tried the code below and encountered some issues. When I click the button, I want to add the <option value= ...

Creating a smooth JQUERY fade slideshow with seamless transitions, no white gaps in

I am having trouble with the slideshow on my Wordpress website www.2eenheid.de. I want the images to fade smoothly between each other instead of fading into a white background color first and then into the next image. Can anyone help me find a solution for ...

The chart refreshes whenever there is a change in the component's state

Whenever I click the button to use the changeState method, the state changes and the MoreInfo component appears. However, the chart is being drawn again as shown in this GIF: Below is the code snippet: import React from 'react' import './Ho ...

Ensuring the canvas fits perfectly within its parent div

I am attempting to adjust my canvas to fit inside a div. // Make the Canvas Responsive window.onload = function(){ wih = window.innerHeight; wiw = window.innerWidth; } window.onresize = function(){ wih = window.innerHeight; wiw = window.innerWidth; } // ...