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

Disabling prefetch in next.config.js: A comprehensive guide on eliminating data prefetching in Next.js

Typically, in many cases, the disabling of prefetching is achieved by specifically setting a link to not preload. An example of this can be seen below: <Link href="/about" prefetch={false}> <a>About us</a> </Link> My go ...

To access the link, simply click once if there is no child menu. However, if there is a child menu attached, be sure to click

I am working on a mobile menu that is designed to slide out when clicked. Currently, the parent pages are displayed by default. I want to implement functionality where if a parent page has child pages, clicking on it will slide down the sub menu. If click ...

Automatically reduce the size of Java Script files and CSS files with compression

I'm currently working with Google App Engine and JQuery. I'm looking for a solution that can automatically compress my JavaScript and CSS files when deploying them to the GAE server. It's quite cumbersome to manually compress all the files e ...

How can a JQuery slideshow be programmed to only iterate once?

Looking to create a slideshow that transitions between images every two seconds? Check out the code snippet below: HTML: <div class="fadeIn"> <img src="img/city.png" class="remimg" id="city"> <img src="img/shop.png" class="remimg" ...

The UI in an angular directive is not getting refreshed due to issues with the

Check out this fiddle http://jsfiddle.net/3jos4pLb/ I have a problem where my directive communicates with the parent controller scope by setting the finalValue. However, when the window is resized, the scope.finalValue updates in the console but the UI d ...

Question about React.js: What is the best way to add multiple classes to a component by using a ternary operator?

I am looking to apply multiple classes to a component by utilizing a ternary operator. In our shared ts theme file, we have the general button styles defined, but for this specific component, I want to adjust the sizes based on screen width. To achieve thi ...

Detecting single letters in a sentence and changing their appearance using CSS

Looking to make a subtle change to text? I need to swap out single letters in a passage (I have a cat that ate a fish). Any ideas on how to do this? The goal is to input a block of text into a textbox, then display it in a div. I've had difficulty fi ...

Introducing a fresh Backbone object attribute that points to an existing instance property

While working with Backbone/Marionette, I came across something unusual. When I create a new instance of a view with a new collection property and then create another instance of the same view, it seems that the collection property of the second view point ...

When hovering over a select option, a description and clickable link will be displayed

I need to display a description with a clickable link when hovering over any option in the select tag. <div class="col-lg-4"> <div class="form-group"> <label class="form-label">Goal</label> <select name="semiTaskType ...

The combination of Angular Hottowel's 'blocks.exception' and 'blocks.router' prevents the App from being displayed in the browser

After delving into Angular's fundamentals a couple of months back, I am now venturing into building a practice app that mirrors industry standards. I recently completed John Papa's Play by Play and Clean Code courses on Pluralsight, which furthe ...

Cross-origin resource sharing problem arises when JavaScript is loaded asynchronously using script tags created dynamically

By dynamically creating a script as shown below, the JavaScript source is downloaded asynchronously. let newScript = document.createElement('script'); newScript.src = srcUrl; let firstScript = document.getElementsByTagName('script')[0] ...

Exploring the mocking of document,hidden using Jasmine

Struggling to simulate document.hidden in an angular unit test, but facing issues. Tried the following solutions: spyOn(Document.prototype, <any>'hidden').and.returnValue(true); spyOn(Document, <any>'hidden').and.ret ...

Ways to extract information from a JSON dataset

[{"id":7,"message":"This is just a sample message","taker_id":"131","giver_id":"102","status":"0","stamp":"2016-08-11"}] Here is my answer. I am attempting to retrieve some data. I have attempted using data.id but it is unsuccessful and gives me undefined ...

The variable from AJAX is not being displayed in PHP

Need help with transferring a JavaScript variable to the same PHP page. The following code is what I have so far: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script& ...

Turn off the authentication middleware for a particular HTTP method on a specific endpoint

Currently, I am using Express/Node and have developed authentication middleware to validate JWT on each request. My requirement is to disable this middleware for a specific route (POST '/api/user/') while keeping it active for another route (GET ...

Using Express Router to call a dynamic route instead of the intended named route

I'm currently developing an API using Express.js, implementing routes and controllers. Within my api.js file, I have the following setup: const app = express() app.use('/clients', clients) Then, in my router/client.js file, I specify the e ...

the term 'this' does not pertain to the user object within the mongoose model

Here is a snippet of my code that saves a user object to a database using Express: api.post('/signup', function (req, res) { var user = new User(); user.name = req.body.name; user.email = req.body.email; user.setPassword(req.body ...

Struggling to make React respond to button clicks without resorting to using addEventListener

Can anyone help me figure out why I can't get the onclick handler to execute in reactjs when specifying it inline for a button? The only solution that worked for me was using addEventListener. From what I understand, this code should work: <button ...

What is the best method for encoding non-ASCII characters in JSON.stringify as ASCII-safe escaped characters (uXXXX) without the need for additional post-processing?

In order to send characters like ΓΌ to the server as unicode characters but in an ASCII-safe string format, I need them to be represented as \u00fc with 6 characters, rather than displaying the character itself. However, no matter what I try, after us ...

Scrolling with React Event

I am attempting to create a scrollbar that only appears when I scroll within a particular area using React. I am utilizing debounce and useState in my implementation. The issue: When I reach the end of the scroll, the event continues to repeat indefinitel ...