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

What steps should I take with my Android PWA manifest and service workers?

I created a web application that I want to prompt Android users to download when they visit. To build my service workers and manifest, I utilized PWA Builder which can be found at Now that I have the manifest file ready, should I simply upload it to the r ...

Navigating the world of cryptocurrency can be daunting, but with the right tools

Hello fellow developers, I've encountered some difficulties with cryptocurrency in my Nativescript project. I am attempting to incorporate the NPM package ripple-lib into my code, but I have been unsuccessful using nativescript-nodeify. How can I suc ...

Creating a map-like scrolling feature for a full-sized image, allowing both horizontal and vertical movement

My goal is to create an infographic image that can be scrolled horizontally and vertically, zoomed in or out, and where I can add markers just like Google Maps. I attempted the solution of using two scroll views as suggested here: https://github.com/faceb ...

Can webpack effectively operate in both the frontend and backend environments?

According to the information provided on their website, packaging is defined as: webpack serves as a module bundler with its main purpose being to bundle JavaScript files for usage in a browser. Additionally, it has the ability to transform, bundle, or ...

JavaScript code for downloading data through AJAX and then loading a chart is not functioning as expected

<script> var highchartsOptions = { chart: { backgroundColor: 'rgba(255, 255, 255, 0.1)', type: 'column' }, title: { text: '' }, exporting: ...

What is the best way to handle promises within the context of updating state in React

Recently, I've been working on a React code snippet focused on creating a text input field. onChangeDestination(url, index) { this.setState(prevState => { const rules = [...prevState.rules]; rules[index] = { ...rules[index], url}; ...

Transforming a file with a node module that lacks a .js class into a browseable format

I am currently working on browserifying my module. One of the dependencies I have is on this https://www.npmjs.com/package/chilkat_win32. It is present in my node_modules folder and here is how the structure looks: https://i.stack.imgur.com/uw9Pg.png Upo ...

Checking for the accuracy of the provided full name

There is a specific task at hand: The field labeled “First Name Last Name” must only contain 2 words, with each word being between 3 and 30 characters in length. Additionally, there should be only one space between the first and last name. The issue t ...

utilize dynamic variable within the template's views

Here is a snippet of my HTML code var marker; function initMap() { map = new google.maps.Map(document.getElementById("mymap"), myOptions); getMapMetadata([]); // setInterval(function(){ getMapMetadata([]); }, 3000); } function createMarke ...

Ways to execute additional grunt tasks from a registered plugin

I am currently in the process of developing a custom Grunt plugin to streamline a frequently used build process. Normally, I find myself copying and pasting my GruntFile across different projects, but I believe creating a plugin would be more efficient. Th ...

Fade or animate the opacity in jQuery to change the display type to something other than block

I am currently using display: table and display: table-cell to vertically align multiple divs. However, I have encountered an issue when animating the opacity with jQuery using either fadeTo() or fadeIn. The problem is that it always adds inline style di ...

The issue with mocking collections using JSON files in Backbone is that it is not properly triggering the success callbacks in

For my project, I am exploring the use of .json files to mock GET requests in a backbone collection. Here is an example of my sample file: [ { "id": '11111', "name": "Abdominal Discomfort", "favori ...

Can you explain the distinction between querying a database and making a request to an endpoint?

Recently, I've been diving into learning mongoose but came across a code that left me puzzled. I'm curious as to why we include the async keyword at the beginning of the callback function when querying a database. Isn't it already asynchron ...

Delete any HTML content dynamically appended by AJAX requests

I'm currently working on a page dedicated to building orders, where the functionality is fully dependent on ajax for finding products and adding them dynamically. However, I encountered an issue when attempting to remove an item that was added via aj ...

Tips for creating an animation for transferring a task between two lists using Vue.js?

Attempting to replicate the moving animation in a Svelte example using Vue.js. Here is my progress so far. Simply click on the todo items to view them. new Vue({ el: "#app", data: { items: [ { id: 1, name: 'John', done: false }, ...

The reason behind the successful execution of the final .then in promise chaining

I am new to JavaScript and have encountered an interesting problem with the following code. Even though I haven't returned anything from the .then method, the last .then (blue color) works instead of the first one (red color). Can someone explain why ...

Inserting HTML content into a DIV with the help of jQuery

Looking for a solution with my index.html file. I want to load other HTML files into a DIV by clicking on buttons. Here's an example of what I'm trying to achieve: I've searched through various examples online, but none seem to work for ...

Dynamically extract key values from JSON data and display them on an HTML page with checkboxes for selection. Generate a new JSON object containing

I am facing the challenge of parsing an unknown JSON with uncertain key-value pairs. As I do not have prior knowledge of the keys to access, my goal is to traverse through every key in the JSON and display all keys and their corresponding values on the scr ...

Selecting properties from a GeoJSON object on the fly with Leaflet

I am currently attempting to dynamically modify the displayed property on my leaflet map. Below is the code I have been working with: $("#button_thermal").click(function(){ $.getJSON("physicalProperties.geojson", function(data) { var geojson2 = L.geoJson( ...

Encountering an npm error: How can I install compiler-sfc that satisfies the peer dependency requirement for @babel/core?

Review of my packageJSON "devDependencies": { "@fortawesome/fontawesome-svg-core": "^1.2.35", "@fortawesome/free-solid-svg-icons": "^5.15.3", "@vue/compiler-sfc": "^3. ...