Is it possible to sort by two properties where one takes precedence, even if they share common values?

Query: Can you guide me on sorting my data array based on two criteria:

  1. Ensure that the type is prioritized at the top.
  2. Arrange the counts from smallest to largest.

Here's what I've tried so far:

var data = [
  {type: 'first', count: '1'},
  {type: 'second', count: '5'},
  {type: 'first', count: '2'},
  {type: 'second', count: '2'},
  {type: 'second', count: '1'},
  {type: 'first', count: '0'},
]

//Expected Output
var newData = [
  {type: 'first', count: '0'},
  {type: 'first', count: '1'},
  {type: 'first', count: '2'},
  {type: 'second', count: '1'},
  {type: 'second', count: '2'},
  {type: 'second', count: '5'},
]

 //**Pseudo code**//
// Sort by type first
data.sort((a,b) => a.type === 'first' ? -1 : 0)

// Then sort by count 
data.sort((a,b) => a.count < b.count ? -1 ? (a.count > b.count ? 1 : 0)

I'm facing challenges in dealing with shared count values among different types. How can I achieve sorting based on both properties while maintaining the hierarchy of type and order of count?

Answer №1

To arrange the data in a specific order, you can utilize the sort() method.

var info = [
  {category: 'apple', quantity: '5'},
  {category: 'banana', quantity: '12'},
  {category: 'apple', quantity: '8'},
  {category: 'orange', quantity: '3'},
]

var sortedInfo = info.sort(function(a, b) {
  return ((b.category == 'apple') - (a.category == 'apple')) || (a.quantity - b.quantity)
})

console.log(sortedInfo)

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

Load various information retrieved from an HTTP API into a SQLite database

I am currently working on an Ionic2 project that requires users to log in before gaining access to the system. Once the login is successful, I need to post their username to another API to retrieve a list of all entries made by them. The challenge I am fac ...

The marriage of Vue 2.0 and Rails 5: Shifting from Reactive to Declarative Rendering

As I make my way through the Vue guide with a Rails 5 app, I've noticed that although I am able to update my Vue js object, the DOM doesn't behave as described in the Declarative Rendering section. The data and the DOM are supposed to be linke ...

Execute a particular NodeJS function within the package.json scripts section

I've got a NodeJS file with an export function that looks something like this: test.js exports.run = function(){ console.log('You execute this function!'); }; Is there a way to trigger this function specifically by using a custom comman ...

What is the best way to include a date range together with other placeholder variables in a PostgreSQL and Express setup?

Forgive me for what may be a basic question, but as I dive headfirst into teaching myself SQL & PostgresSQL, I've stumbled upon an issue. I'm attempting to insert a large number of placeholders into an INSERT statement, but I'm struggling t ...

nodemailer failed to authenticate login: 535 Authentication Error

I'm encountering a 535 Authentication Failed error when trying to utilize the nodemailer npm package in my node application for sending emails through the contact page. My email and password are correct, so I'm unsure why this issue is arising. v ...

Ways to determine if an object contains an array

Looking at the following data structure: [ 13, { a: [ [ '2988.30000', '0.19000000', '1549294216.653040' ] ] }, { b: [ [ '2988.30000', '0.00000000', '1549294216.653774&a ...

Determine if all resources on a page in Angular 4 have finished loading by keeping a loader spinning until everything is fully loaded

As part of my work on an Angular app, I am developing a loader to enhance user experience. While the typical approach involves utilizing a boolean parameter for subscribing to HTTP requests, in my case, the service's response consists of multiple ima ...

Localizing HTML number input values is not functioning properly

When using an HTML number field, I encountered the following error: The specified value "101,5" is not a valid number. The value must match the regular expression: -?(\d+|\d+\.\d+|\.\d+)([eE][-+]?\d+)? I am trying to co ...

Creating TypeScript domain objects from JSON data received from a server within an Angular app

I am facing a common challenge in Angular / Typescript / JavaScript. I have created a simple class with fields and methods: class Rectangle { width: number; height: number; area(): number { return this.width * this.height; } } Next, I have a ...

Field for Entering Time

I need help creating a form that will only accept time values formatted as HH:MM. Can someone guide me on how to filter user input and display the colon in the text field? I am thinking that I might need a specialized input box for this purpose. ...

The documentation for Gridsome/Netlify CMS has a flaw that results in Graphql not functioning

My attempts to integrate Gridsome with NetlifyCMS using Gridsome's documentation have been unsuccessful. Below is a snippet of the Netlify config.yml setup: collections: - name: "posts" label: "Posts" folder: "posts" create: true s ...

The video attribute in HTML is malfunctioning on the react webpage

Currently working on setting up a basic portfolio layout with a video playing in the background on loop. However, despite making some adjustments and modifications, the video is not showing up as expected. Any insights or suggestions on what might be causi ...

Remove webpack functions from the bundle

After following a comprehensive tutorial on bundling files with webpack and some additional online research, I successfully created a configuration file that organizes the modules in my library into the specified structure: dist/node/weather.min.js dist/we ...

Why doesn't express.js throw an error when the variable 'app' is used within its own definition?

When working with express.js, I find it puzzling that createApplication() does not throw an error. This is because it uses app.handle(...) within an anonymous function that defines the same variable 'app'. I attempted to replicate this in jsFidd ...

Sharing props in React.js among distinct child components using a centralized parent component

I am currently working on developing a front end console using React, which includes a side menu for filtering results from a database and displaying them in a dynamically generated table. The component hierarchy is structured as follows: App.js | |--Sid ...

Sneaky spam and ads embedded within Joomla template

Today, while examining the source code of a Joomla site I am developing, I stumbled upon some hidden links that seem to be spam. I have spent an hour searching through various template files but have been unable to locate them. The hidden links in questio ...

Reposition picture "overlays" additional HTML components

I am struggling with rotating an image by clicking on a button as the image overlaps the buttons. Can anyone provide guidance on how to achieve this without overlapping? For reference, here is my code and an example: here (http://jsfiddle.net/jj03b17n/5/) ...

Merge JSON objects while retaining duplicate keys

I am looking to merge two arrays containing JSON objects while retaining duplicate keys by adding a prefix to the keys. In this specific scenario, the data from 'json2' is replacing the data from 'json1' due to having identical keys, bu ...

Counting elements in an optional array in Swift

When working with Objective-C, and having the property as shown below: @property (strong, nonatomic) NSArray * myArray; The method to determine the number of objects in myArray would be: - (NSInteger) numberOfObjectsInMyArray { return [self.myArray ...

Tips for deploying a Nuxt application using an alternative command line interface

Despite my best efforts scouring the internet for a solution, I have yet to find a method to resolve my issue. The problem lies with my nuxt.js SPA being blocked by my company firewall when accessed by other users at the designated host/port. While servin ...