The issue of array sorting, specifically the function(a, b) {return b.value - a.value), is causing some

I am struggling to retrieve data from firebase and sort them according to the field 'overallScore' in descending order. Despite following suggestions like using array.sort(function(a, b) {return b.value - a.value), I have not been successful in sorting the array as expected.

The structure of my firebase data is illustrated here:

https://i.stack.imgur.com/ZNQ5M.png

Below is an excerpt of my code:


getAll: function(){
  database.collection('Users').get().then(querySnapShot => {
    let data = [];
    querySnapShot.forEach(doc => { 
        data.push(doc.data())
    })
    this.datasets = data;
    this.getTop();
  })
},
getTop: function(){
  var today = String(moment(String(new Date())).format("DDMMYYYY"));
  var top = [];
  for (var i = 0; i < this.datasets.length; i++) {
    if (this.datasets[i].scoreDate == today){
      top.push(this.datasets[i]);
    }
  }
  top.sort(function(a, b){return b.overallScore - a.overallScore});
  this.top10 = top;
},

Upon examining the console log result after running the code, the output appears as shown below:

https://i.stack.imgur.com/oAlHM.jpg

Answer №1

The sort() method in JavaScript provides three possible return values: 1, -1, or 0

arr.sort(function (a, b) { return a.age > b.age ? 1 : a.age < b.age ? -1 : 0 });

Answer №2

Modify the sort function to compare overallScore values as follows: a.overallScore - b.overallScore

let topScores = [
  {overallScore: 1},
  {overallScore: 2},
  {overallScore: 8},
  {overallScore: 12},
  {overallScore: 4},
  {overallScore: 5},
  {overallScore: 3},
  {overallScore: 29},
]

topScores.sort(function(a, b) {
  return (a.overallScore - b.overallScore);
});

console.log(topScores);

Visit this link for live demo!

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

Tips for showing a variety of headers on your page

I am struggling to align multiple headers on the same horizontal line. Despite my efforts, only two of them display correctly while the third keeps dropping down a line. To see what I mean, take a look at this image: view current layout Here is the code ...

Obtain unique entries from a Firestore collection search

Seeking assistance in filtering an observable to only contain unique records. I am using the observable in an angular mat-autocomplete with an async pipe and querying firebase based on the user's input. The code for the mat-autocomplete template: ...

Focusing solely on a particular category in EJS

I am struggling with this code snippet. HTML: <header<% if ( current.source === 'features' || current.path[0] === 'index' || current.source !== 'customers' ) { %> class="header-white"<% } %>> <div cl ...

Retrieve the route.js directory using Node.js

My server.js file is located in the directory: /dir1. To start the server, I use the command node server.js. In the directory /dir1/app/, I have my file named routes.js. I am trying to find out the directory path of the server.js file. However, I am unc ...

finding the current page id in Vue.js and Laravel: step-by-step guide

Focusing on my blog project using Laravel and Vue.js, I have developed the comment section as a Vue component and integrated it into the show function of my post like this: @section('content'); . . . <comment></comment> @end ...

Problem with Handlebars: When compiling, TypeError occurs because inverse is not recognized as a function

I've hit a roadblock with an error that I just can't seem to solve. My goal is to dynamically compile a template extracted from a div on the page, provide it with content, and then display it in a designated area of my webpage. Here's the s ...

Attaching an External JSON Data File in JSFiddle

Can external JSON Data be linked within JSFiddle? Here is the code snippet I'm using to fetch the JSON Data: var xhr = new XMLHttpRequest(); xhr.open('GET', url: 'www.myurl.com/js/data/data.json', true); xhr.send(null); I have ...

Using Selenium: Checking for existing dropdown values and incrementing if necessary

I am currently working on automating an application using Selenium Webdriver with Java. The web application I am testing has an Add button that, when clicked, triggers the activation of a dropdown menu. Subsequent clicks on the Add button reveal additional ...

Implement the morgan express middleware from exports

For my logging needs in an Express application, I have decided to utilize the morgan package. Initially, I was able to integrate morgan by using it directly in my server.js file like so: app.use(morgan('tiny')), which worked perfectly. However, I ...

Exploring the functionality of URLs in Node.js

I am working on testing an array of URLs to ensure that each one returns a 200 response code. So far, I have written the following code to accomplish this task. However, I have encountered an issue where only the last URL in the array is being tested. How ...

Angular: Array in the template re-renders even if its length remains unchanged

Below is the template of a parent component: <ng-container *ngFor="let set of timeSet; index as i"> <time-shift-input *ngIf="enabled" [ngClass]="{ 'mini-times' : miniTimes, 'field field-last&ap ...

When onSucess is called within a Vue view, the metadata parameter returns undefined, whereas it works properly inside a

In my Vue component for Plaid Link, there is a function/action in my Vuex store called onSuccess. This function is supposed to call my backend API to exchange the public token for an access token and send some data about the link to the backend. However, I ...

Generating interactive child posts for a specialized post type in WordPress

I am currently in the process of planning a simple plugin and am searching for ideas on how to add subposts (child) for posts in WordPress directly on the post creation page. I would like to incorporate a form with two fields, title and content, and have ...

Tips for overriding ng-disable in AngularJSUnleashing the

This is a comment box using AngularJS: <tr> <td colspan="5"><br/>Comments* <div><textarea class="form-control" rows="3" cols="60" ng-model="final_data.drc_scope" placeholder="Add comments here" ng-disabled="is_team==0 || isDis ...

A guide on retrieving and resetting the value of a radio button within a table

I need to create multiple radio buttons within a table using Razor syntax under ASP.NET Core MVC. Each row of the table should have an update and clear link to update the record and clear the selected radio button for that specific row. <table class=&qu ...

Purging the JavaScript output

Currently, I am calling an API and receiving a list of results. These results are then processed into an object for iteration and display. Below is the function responsible for this process: var getAvailability = () => { if (chosenData.hot ...

What is the process for uploading SVG files created by users onto the server?

After dedicating three full days to researching, I have hit a roadblock in my attempts to allow users to upload SVG files to the server on my website. I created an HTML and Javascript platform where users can input dimensions into a form to create a basic ...

Unlocking the Power of Global Props in AlpineJS: A Step-by-Step Guide

I'm currently exploring AlpineJS after having some experience with React and basic knowledge of Vue. One thing that has puzzled me about AlpineJS is how to update a state value from within a function, similar to how it's done in React. Let' ...

Determine the amount of clicks and retrieve the URL of the clicked link in Selenium using Python

As a novice in the world of Selenium and Python, I am embarking on the journey of automating banner testing using Python along with Selenium Webdriver. My goal is to keep track of the number of clicks made, ensure that the URLs are redirecting to the corr ...

Type Vue does not contain the specified property

I am encountering an issue where I am using ref to retrieve a value, but I keep receiving the error message "Property 'value' does not exist on type 'Vue'". Below is the code snippet causing the problem: confirmPasswordRules: [ ...