Achieving the perfect sorting result in an array using Javascript

I am attempting to arrange the objects inside an array below in ascending order by their values and achieve the desired output as shown:

var arr = [{"DOA Qty":"0.000665921017598927382910198160","LOS%":"0","FID Valid EC By Part":"0.0041860443283016713761966","Interventions":"0"}]

Desired output - sorted in ascending order by value:

var desiredarr =[{"LOS%":"0","Interventions":"0","DOA Qty":"0.000665921017598927382910198160","FID Valid EC By Part":"0.0041860443283016713761966"}]


let sorteddataarr: any = Object.values(arr[0]).sort(function (a, b) { return arr[a] - arr[b]; });

alert(JSON.stringify(sorteddataarr));  // not displaying the expected result

Answer №1

a[1]-b[1] == :ASEC

b[1]-a[1] == :DESC

Give this a shot:

var data = 
{
"DOA Qty":"0.000665921017598927382910198160",
"LOS%":"0",
"FID Valid EC By Part":"0.0041860443283016713761966",
"Interventions":"0"
}

var entries = Object.entries(data)
entries.sort(function(a,b){return a[1]-b[1]});

data = {};
entries.map(function(item){
data[item[0]] = item[1];
})
console.log(data);

Answer №2

If you're looking to maintain a specific order when dealing with object keys, there is a workaround. By converting the object(s) into array(s) of key(s) and value(s), you can ensure that the order remains intact:

var arr = [{"DOA Qty":"0.000665921017598927382910198160","LOS%":"0","FID Valid EC By Part":"0.0041860443283016713761966","Interventions":"0"}];

console.log(
  arr.map(
    object=>
      Object.keys(object).map(
        key=>[Number(object[key]),key]//consider creating better JSON if your values are not numbers
      ).sort(
        ([a],[b])=>a-b
      )
      //if you prefer [key,value], you can use .map(([value,key])=>[key,value])
  )
)

Answer №3

Let's create a straightforward compare function to sort an array based on a specific key. In this case, we will be using the "value" key.

To implement this, we first need to define our compare function and then utilize Array.prototype.sort() by passing in our custom compare function.

The only distinction between arranging the array in descending or ascending order is the manipulation of greater than and less than symbols within the compare functions.

function compareDESC(a, b) {
  if (a.value < b.value)
    return 1;
  if (a.value > b.value)
    return -1;
  return 0;
}

function compareASC(a, b) {
  if (a.value > b.value)
    return 1;
  if (a.value < b.value)
    return -1;
  return 0;
}

var arr = [
  {
    value: 2
  },
  {
    value: 6
  },
  {
    value: 3
  },
  {
    value: 8
  },
  {
    value: 9
  },
  {
    value: 4
  },
];

arr.sort(compareDESC)
console.log(arr)
arr.sort(compareASC)
console.log(arr)

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

A JavaScript function that fetches the color name based on either the RGB value or the Hexadecimal value

Looking for a JavaScript function that can determine the name of a color. Would like the JavaScript function to be structured as shown below: function getColorName(r, g, b) { .... return <color name>; // such as blue, cyan, magenta, etc. } ...

What could be the reason for the absence of definition for 'res'?

As I work on coding a bot using discord.js, I am facing an issue while trying to set up a system where the bot can send a message as long as it is not blacklisted. However, every time I attempt to run the function, I encounter this error message: Reference ...

Utilizing HighCharts' Reflow Feature for Dynamic Chart Resizing

Our Angular application utilizes highcarts-ng for implementing HighCharts. Check out the Chart Maximize and Minimize function that is currently operational: function expandChartPanel() { vm.chartMaxed = !vm.chartMaxed; viewHeader = ScopeFactory. ...

What steps are involved in testing a nextjs endpoint with Jest?

One of my challenges is an endpoint responsible for user sign up: import { createToken } './token'; // Unable to mock import { sendEmail } './email'; // Unable to mock export default async function signUp( req: NextApiRequest, res: ...

The value of req.user is not defined in a stack involving node, express, passport,

When I use console.log(req.session); I receive the message: Session {cookie:{ path: '/',_expires: null,originalMaxAge: null,httpOnly:true },passport: { user: 5b427a2d117d7c3f6087db8a } } However, when using console.log(req.user); I get un ...

Concealing overflow in a sticky container when a fixed child element is present

I am currently working on a website where I have implemented slide-up section panels using position: sticky while scrolling. However, I am encountering issues with fixed elements within the sticky panels not properly hiding outside of the respective sectio ...

Please disable zoom functionality on the website specifically for Android devices

Is there a way to disable the zoom feature on our website specifically for Android phones/devices without affecting iPhones? Perhaps targeting the Chrome browser on Android would be sufficient, but we should also verify the mobile screen size. ...

Populate a form with database information to pre-fill the fields

So I have this web form built with HTML, and there are certain values within the form that can be changed by the user. To ensure these changes are saved, I'm storing them in a database. My goal is to have the form automatically filled with the data fr ...

Give the Row ID as a parameter to a personalized component within MUI Datagrid Pro

I am currently exploring the idea of incorporating an intermediate state to row checkboxes based on the selection status of other checkboxes within a detailed panel. My approach involves crafting a custom checkbox component and implementing some logical ...

How can I easily swap between the front and back cameras while using an app?

Trying to create a web-ar experience that allows users to switch between front and back cameras while utilizing SLAM/6dof with the back camera has been a challenging endeavor. While attempting this in PlayCanvas, I faced difficulties getting the front came ...

What is the method used by three.js to render video with spherical UV mapping?

I have a streaming video displayed in a 3*3 format. I am able to splice the entire video into individual sections using THREE, // Creating a 3x3 PlaneGeometry var geometry = new THREE.PlaneGeometry(400, 200, 3, 3); const video1 = document.getElem ...

Importing data from a CSV file into a Google Spreadsheet using the Python programming language

I am currently working on a Python script to transfer data from a CSV file to a Google Spreadsheet. While I have a good grasp of the fundamentals required for this project, I am struggling with formatting and parsing the data from the CSV file into the Goo ...

Retrieve the text content of a datalist option by accessing the label with jQuery

Utilizing data from a Json, I am populating a data-list in html. The options are added to the data-list with both value and label text. Upon clicking an option, I aim to insert both the value and text into a form text field. While accessing the option&apo ...

The sequence of divs in a language that reads from right to left

Is there a way in HTML to designate a set of divs so that they automatically align from left to right for languages that read left to right, and alternatively, flow from right to left for languages that read right to left? This means that the direction of ...

What is the best way to create a new variable depending on the status of a button being disabled or enabled

Imagine a scenario where a button toggles between being disabled when the condition is false (opacity: 0.3) and enabled when the condition is true (opacity: 1). Let's set aside the actual condition for now -- what if I want to determine when the butt ...

Converting numbers from a string into a character array and then into an array of

I am currently working on a task that involves converting a string input into a character array and extracting the numbers from it for use in a credit card program. Here is my approach: During my current process, I encountered a Null Pointer Exception at ...

Resolving "Module not found: Error: Can't resolve 'url'" issue in Angular 14 while invoking web3 smart contract function

How do I resolve the web3-related errors in my Angular 14 dapp? I attempted to fix the issue by running npm i crypto, npm i http, and more. Every time I try to call a function from a smart contract with code like this.manager = await report.methods.mana ...

Using axios.spread() allows for caching of my API requests, a feature that is not available when

Thank you for taking the time to read this. I find myself in a peculiar situation where I am required to invoke multiple CMS API routes from my server to incorporate their response.data into an object that will later be transferred to the client side. The ...

Javascript timer that counts down using cookies for storage

Seeking assistance - I am in search of a solution to create a javascript countdown timer that utilizes cookies. I need the timer to remain consistent even when the user refreshes the page, until a specific time has elapsed. This is for an online examinat ...

Transforming jquery code into angularjsAre you looking to migrate your

I am currently struggling with converting a jQuery function into an AngularJS function. Here is the specific code snippet: $('p').each(function() { $(this).html($(this).text().split(/([\.\?!])(?= )/).map( function(v){return '< ...