Arrange a collection of objects based on their values even when the key is subject to change

I need help sorting an array of objects as shown below.

var obj = [{"UMAIR":410},
        {"ALI":2177},   
        {"JOHN":410},
        {"ANTHENY":410},
        {"FRANKLY":410},
        {"FRONTY":534},
        {"SLIM":534},
        {"ASFUND":534}];

I want to sort the objects based on their integer values. I came across the following code online and I'm trying to understand how it works:

 obj.sort(function(a, b) {
    return a.price - b.price;
});

The code snippet above is using the price property to sort the objects, however, in my case I don't have a specific property like that.

Answer №1

One possible solution is to utilize the sort function...

obj.sort(function(a,b) {
   return a[Object.keys(a)[0]] - b[Object.keys(b)[0]];
});

This code snippet is essentially the same as:

obj.sort(function(a,b) {
   var aValue = a[Object.keys(a)[0]];
   var bValue = b[Object.keys(b)[0]];
   if (aValue > bValue)
     return 1;
   else if (aValue < bValue)
     return -1;
   else
     return 0;
}); 

When examining your edits, it seems you have found the solution. It may also be beneficial to explore how to extract elements from JSON, such as using Object.keys in your specific scenario.

Object.keys will generate an array containing the key strings.

Since your object only has a single key, you can access the first value in the array (index 0) and then perform the subtraction between the values from a and b.

a and b represent entries in your array, functioning as objects.

If you refer to this resource, you can gain a better understanding of how the sorting function operates.

Here is an excerpt of code from the provided resource:

function compare(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}

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

Demonstrating the transformation of child elements into parent elements through angular 6 ngFor

I have a JSON array dataset where each object may contain nested arrays. In order to display the inner nested array elements as part of the parent array using Angular's NgFor, I need to format the input like this: [{ 'id': 1, 'tit ...

Angular Tip: Display data in a dropdown using a select element

When I have two select elements and want to display values if they exist: page.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app ...

Starting the download of the canvas featuring a stylish border design

I'm facing an issue where the canvas border is not showing up when I download the canvas with a border. The border appears on the screen, but it doesn't get included in the downloaded canvas. let canvas=qrRef.current.querySelector("canvas&qu ...

Dismiss the pop-up box by clicking outside its borders

I have created a unique homepage featuring pop-up boxes with login fields. The background dims when a pop-up appears, and the user should be able to close the pop-up by clicking outside the box boundaries. Although the function closeOverlay works when the ...

Padding-left in InfoBox

Currently, I am in the process of developing a map using Google Maps API3 along with the InfoBox extension available at this link I have successfully implemented an overall padding to the Infobox using the following code snippet: var infoOptions = { disa ...

What is the best method for breaking down this JSON data into distinct 'objects'?

I am struggling with deserializing JSON data into multiple instances of an object I have defined. Here is how the object is structured: function Question_Value__c () { this.Id=null; this.Name=null; this.Question__c=null; this.Order__c=null ...

Guide on transforming a collection of files from formdata into a JavaScript object

I have a dataset containing multiple images associated with the same product id. import client from "@/lib/fetchWrapper"; export default async function addProductImage({ photo, productId, }: { photo: File[]; productId: string; }) { if ...

Simple JavaScript numeric input field

Hey there, I'm a beginner learning JavaScript. I'm currently working on creating a program that adds numbers input through text fields. If you want to check out the HTML code, visit this link on JS Fiddle: http://jsfiddle.net/fCXMt/ My questio ...

Handling validation errors for arrays in jQuery

I am facing an issue with a form containing multiple input arrays, where I only want certain inputs to be mandatory and apply the class "ignore" to some. The problem is that jQuery validate checks all mandatory inputs. How can I avoid this? Here is a simp ...

The state of the checked value remains unaffected when using the Angular Material Checkbox

I am currently working on a list of elements and implementing a filter using pipes. The filter allows for multi-selection, so users can filter the list by more than one value at a time. To ensure that the filter persists even when the window is closed or t ...

Caution: It is important that every child within an array or iterator is assigned a distinct "key" property

As a new developer in ReactJS, I have created a table using ReactJS on the FrontEnd, NodeJS on the BackEnd, and MySQL for the database. My goal is to retrieve data with a Select request on the table. For my frontend: class ListeClients extends Component ...

The <mat-radio-button> component does not have a value accessor specified

When working with HTML and Angular, I encountered the following issue: <mat-radio-group> <mat-radio-button [(ngModel)]="searchType"> And (Narrower search) </mat-radio-button> <mat-radio-button [(ngModel)]="searchType"&g ...

Ways to exclusively allow cookies from my API server

I am running an Expressjs API server on localhost:4000, and my client on localhost:8008. Is there a way to ensure that my client only accepts cookies originating from my API server? At the moment, I am using fetch with credentials: 'include' to ...

Modifying the key of a JSON file

One of the challenges I'm facing involves handling a JSON file that is being inserted into MongoDB. "entities": [{ "desctype": "Location", "text": "Marília", "relevance": 0.966306, "disambiguation": { "subtype": [ "City ...

Take the inputs, calculate the total by multiplying with the price, and then show

I'm in the process of developing a simple PHP form for an online t-shirt order system. Most aspects are running smoothly, but I'm facing issues with the final calculations. My goal is to combine the quantities based on sizes, multiply them by the ...

Sequential queuing of transitions in CSS3

Is it possible to queue CSS transitions with the same properties? My goal is to translate an element to a specific position (with a transition duration of 0) before translating it again. For example, in this mockup, clicking "move" should move the box 100 ...

Undo a CSS transition when clicked

There is a div named learn-more which expands to fill the whole page when a CSS class is added like this: .learn-more{ padding:10px; font-size: 20px; text-align: center; margin-top:20px; font-family: klight; -webkit-transition:2s; ...

Start the Vue component only after ensuring that the element has been fully loaded

I have created a small vue.js component in JavaScript. Is there an elegant way to instantiate the vue component only when the element is loaded? The problem I am facing is that I'm receiving warnings in other HTML files where the element does not ex ...

Getting the country code using the ng-intl-tel-input directive

How to Extract Country Code from Input in AngularJS I am a newcomer to AngularJS and currently working on a project involving a dropdown for country code and an input field for a mobile number. Upon submitting the form, I am able to retrieve the mobile nu ...

Displaying and hiding a div element using Vue.js dynamically

I have a scenario with two different sized divs: <div class = "bigger"> </div> <div class = "smaller"> </div> The goal is to hide the bigger div and show the smaller div when the screen width is ...