Sort an array by mapping it in decreasing order based on the total sum of its elements

I came across a JSON structure that looks like the following:

{
"user": [
   {"username": "x1", "pfp": "", "scores": [{"easy": 10, "normal": 1, "hard": 2, "oni": 3, "uraoni": 4}]},
   {"username": "x2", "pfp": "", "scores": [{"easy": 3, "normal": 1, "hard": 2, "oni": 3, "uraoni": 4}]},
   {"username": "x3", "pfp": "", "scores": [{"easy": 5, "normal": 1, "hard": 2, "oni": 3, "uraoni": 4}]},
   {"username": "x4", "pfp": "", "scores": [{"easy": 0, "normal": 40, "hard": 2, "oni": 3, "uraoni": 4}]}
]
}

The desired result when ordered by username should be: x4, x1, x3, x2 (x4 with a total of 49, x1 with 20, x2 with 15, and x3 with 13).

I am looking to use the map() function to organize the array based on the sum of the scores.

I attempted to use map for reducing the scores and then sorting it, but encountered difficulties with the reduce() method.

let userscopy = userjson
  userscopy.map((user) => (
    user.scores[0] = JSON.parse(user.scores).reduce((a, b) => a + b)
  ))

https://i.stack.imgur.com/eoWRN.png Any thoughts or suggestions?

Answer №1

To simplify your code, consider creating a helper function called calculateTotal that can be used to calculate the total scores and then sort them accordingly:

const data = {
  user: [
    {
      username: 'player1',
      scores: [{ easy: 10, normal: 1, hard: 2, expert: 3, master: 4 }],
    },
    {
      username: 'player2',
      scores: [{ easy: 3, normal: 1, hard: 2, expert: 3, master: 4 }],
    },
    {
      username: 'player3',
      scores: [{ easy: 5, normal: 1, hard: 2, expert: 3, master: 4 }],
    },
    {
      username: 'player4',
      scores: [{ easy: 0, normal: 40, hard: 2, expert: 3, master: 4 }],
    },
  ],
};

const calculateTotal = (user) => {
  if (user.scores.length === 0) return 0;
  const { easy, normal, hard, expert, master } = user.scores[0];
  return easy + normal + hard + expert + master;
};

const sortedUsers = data.user.sort((a, b) => calculateTotal(b) - calculateTotal(a));

console.log(sortedUsers);

Answer №2

Do you happen to need this information?

const userjson = {
  "user": [{
      "username": "x",
      "pfp": "",
      "scores": [{
        "easy": 0,
        "normal": 1,
        "hard": 2,
        "oni": 3,
        "uraoni": 4
      }]
    },
    {
      "username": "x",
      "pfp": "",
      "scores": [{
        "easy": 0,
        "normal": 1,
        "hard": 2,
        "oni": 3,
        "uraoni": 4
      }]
    },
    {
      "username": "x",
      "pfp": "",
      "scores": [{
        "easy": 0,
        "normal": 1,
        "hard": 2,
        "oni": 3,
        "uraoni": 4
      }]
    },
    {
      "username": "x",
      "pfp": "",
      "scores": [{
        "easy": 0,
        "normal": 1,
        "hard": 2,
        "oni": 3,
        "uraoni": 4
  }]
}

] }

1- .map() is used with arrays, so use userjson.user.map() instead of userjson.map() as the array is inside the user property

2- JSON.parse() should be removed since the json is not valid at the moment

3- Use index for your x.scores[i]

const result = userjson.user.map((x,i) => (
    x.scores[i] = x.scores.reduce((a, b) => a + b)
  ))
  
console.log(result);

Answer №3

const userScores = {
"user": [
   {"username": "x1", "pfp": "", "scores": [{"easy": 10, "normal": 1, "hard": 2, "oni": 3, "uraoni": 4}]},
   {"username": "x2", "pfp": "", "scores": [{"easy": 3, "normal": 1, "hard": 2, "oni": 3, "uraoni": 4}]},
   {"username": "x3", "pfp": "", "scores": [{"easy": 5, "normal": 1, "hard": 2, "oni": 3, "uraoni": 4}]},
   {"username": "x4", "pfp": "", "scores": [{"easy": 0, "normal": 40, "hard": 2, "oni": 3, "uraoni": 4}]}
]
};

const orderedUsernames = userScores.user
  .sort((a, b) => calculateTotalScore(b.scores[0]) - calculateTotalScore(a.scores[0]))
  .map(({ username }) => username);

console.log(orderedUsernames);

function calculateTotalScore(scores) {
  return Object.values(scores).reduce((previous, next) => previous + next, 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

ReactJs CSS - This file type requires a specific loader for processing. There are currently no loaders configured to handle this file

I've noticed that this issue has been raised multiple times before. Despite going through all the questions, I still can't seem to resolve it. The transition from Typescript to Javascript went smoothly until I reached the implementation of CSS. U ...

Having difficulty implementing pagination functionality when web scraping using NodeJS

Currently, I am creating a script that scrapes data from public directories and saves it to a CSV file. However, I am encountering difficulties when trying to automate the pagination process. The source code I am using includes: const rp = require(' ...

I'm curious, which ref tag should I utilize for draft.js?

I'm currently working on a form using Draft.js with Next.js and TS, but I've encountered some errors in my code. Here is what I have so far: import {Editor, EditorState} from 'draft-js'; const [editorState, setEditorState] = useState( ...

Tips for triggering jquery code when a variable containing a CSS attribute is modified

I have a specific requirement where I need to reset the scrollleft value to 0 on my wrapper whenever a particular CSS property changes. Although I am new to using jQuery and haven't worked with variables much, I believe I need to create a variable to ...

Display visual information without requiring the parameters to be filtered beforehand in vue.js

Upon opening my page, I encountered an issue where the graphics appear blank. This is because I set up the callback for generating graphic data through params request. I wish to first fetch the general data when the page opens, and only load with params w ...

Unable to upload file on ReactJS platform

I'm facing an issue while trying to upload a file and text using a form. The file doesn't get uploaded, although it works fine with Postman. Can anyone identify the problem? Thank you Axios function : postArticles : (content, attachment, header ...

Alter the Cascading Style Sheets (CSS) value by accessing a

I have two files, keyboard.css and keyboard.js. My objective is to modify a CSS rule: .ui-keyboard div { font-size: 1.1em; } Is there an alternative method to change the font size without utilizing $(".ui-keyboard div").css()? I want the modification ...

Angular Translate Directive Unleashes the Power of XSS Vulnerabilities

For my project, I have chosen to utilize the 'escape' method as the sanitization strategy for handling potentially harmful content. This includes implementing the translate directive in certain areas, as well as utilizing the translate filter in ...

Some of the Tailwind CSS colors may not be fully supported by Next.js for rendering

Don't forget to showcase all the amazing Tailwind CSS Colors, Sometimes they go missing unexpectedly, and only a few decide to make an appearance. I try to add them manually one by one, but sometimes they just don't show up on the map. Edit: ...

What is the best way to eliminate YouTube branding from a video embedded in a website?

I am currently utilizing an <iframe width="550" height="314" src="https://www.youtube.com/embed/vidid?modestbranding=1&amp;rel=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe> This setup removes the "YouTube" logo from the ...

Navigating the issue of "Experiencing additional hooks rendered compared to the previous render"

I'm currently in the process of developing a small application where certain elements will be nested within one another. My approach involves segmenting each component into its own file (children), returning a function with two components in each Rend ...

After upgrading from Next.js 14.1.0 to 14.1.4, I encountered an error stating that the session cookie exceeds the allowed 4096 bytes limit in Next Auth

I recently updated my NextJs frontend to version 14.1.4 and encountered an authentication API error when using Next-Auth with Express as the backend. Reverting back to the previous version (14.1.0) resolved the error, but now I am facing a new issue while ...

Using Express and Node.js to implement the Google Maps API

Currently working on creating a simple web application using the Google Maps API with express/node. At the moment, I have three main files that make up my project: server.js const express = require('express'); const bodyParser = require(' ...

When attempting to access API>19 on my Android device, I encountered an error in my Interface to Java that stated: "TypeError: Android.method is not a function."

Having my minimum API set to 16, everything seems to be working fine. However, debugging has become quite a challenge. I've read that after API 19, the Chrome debugger can be used. But when it comes to interfacing with Java code, I encounter the error ...

Sending Python Object from Django View to Javascript Script in Template

Here is a basic code snippet created solely to illustrate a problem. While the task at hand can be achieved without JavaScript, I am exploring how to accomplish it using JavaScript for my actual code where it is necessary. In view.py Inside the play_game ...

Occasionally, the render process may be delayed by the Next.js buildManifest and ssgManifest

I've encountered a puzzling issue with my self-hosted Next.js v12.1 setup. Sometimes, the nextjs chunks, ssgManifest, and buildManifest scripts appear as render-blocking in webpage tests, while other times they do not. Interestingly, on mobile devices ...

Encountering Error 500 with Jquery Min.Map File

ERROR: GET request to http://domain.com/assets/js/jquery-1.10.2.min.map returned a 500 Internal Server Error Can anyone help me figure out what's causing this error? I checked the log files in /var/log/error but couldn't find any information. T ...

Storing the order of jQuery UI Sortable in the WordPress Admin Panel

My goal is to customize the order of taxonomy terms for each individual post in Wordpress. I have created a metabox on the EDIT POST page that contains custom taxonomy terms and made them sortable using JQuery. Here is my setup on the Wordpress backend: ...

Updating text color with Ajax response value

I need assistance with updating the text color of a sensor value displayed using html/ajax. Currently, the sensor value is being displayed successfully, but I want the text color to change based on the value. Here's an example: if value < 50 then f ...

Encountered a CLIENT_FETCH_ERROR when attempting to access getSession within the apollo context

While working on my application, I integrated Next-Auth in the frontend and Apollo server in the backend. This is the code snippet from my backend: const server = new ApolloServer({ schema, csrfPrevention: true, cache: 'bounded', ...