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

What is the best way to denote arrays in ember-data models?

When dealing with an array in a model, is it essential to use DS.hasMany pointing to a DS.Model, even if the array elements are not actual models with IDs or endpoints? Is there a more efficient alternative? Despite using DS.hasMany with { embedded: true ...

The JavaScript .load() function fails to run

Attempting to create a straightforward Newsfeed page based on user interests. Here is the code I have implemented for this purpose. The issue I'm facing is that while the code works fine on my local server, it encounters problems when running on an on ...

What is the easiest way to include a copyright symbol in a React component?

I am trying to include the copyright symbol in a React component, but it doesn't seem to be working for me. function Footer() { return ( <footer> <p>&copy</p> </footer> ); } <p>&copy</p> ...

The choice between using inline style objects with React or utilizing traditional CSS classes presents distinct advantages and

Is there a discernible difference between utilizing an inline style object for react components and using a normal CSS class through the className attribute? Even when wanting to modify styles based on a specific event, simply changing the className should ...

Incorporate fresh Google sites into different web pages using iFrame integration

Wishing you a fantastic day! I am currently working on embedding a brand new Google site into another webpage. I attempted to use an iframe for this purpose, but unfortunately it did not work as expected. Here is the code snippet: <iframe width="1280 ...

What is the best way to create a Div element that functions as a button, becoming active when clicked while deactivating all other Div elements

function toggleButton1() { $("#button1").toggleClass("button-active button-inactive"); $("#button2").toggleClass("button-inactive button-active"); $("#button3").toggleClass("button-inactive button-active"); } function toggleButton2() { $("#butto ...

How can I prevent a repetitive div from appearing in a JQuery show/hide function?

Whenever I trigger my AJAX function, the loading image keeps repeating every time I click on the next page. I want to prevent this repetitive loading image and only display it once when I go to the next page. To address this issue, I created a <div cla ...

Enhance the size of dynamically generated svg elements by scrolling the mouse wheel in and out

In my ASP.NET application, I have a view page where SVG elements are dynamically generated. Now, I want to implement zoom functionality for all the created SVG elements. Zooming in should occur when scrolling up and zooming out when scrolling down. <sv ...

Dynamic horizontal scrolling

I need help implementing a site using React that scrolls horizontally. I'm unsure how to implement certain aspects, so I am looking for some assistance. Within a wrapper, I have multiple container Divs. <div class="wrapper"> <div class=" ...

The barcode is not displaying when using javascript:window.print() to print

I am currently developing a Mean Stack App where I have a requirement to display a barcode. To achieve this, I am utilizing an AngularJS directive for generating a 128 barcode, and it is being generated successfully. However, when I attempt to print by cli ...

Searching for an array of IDs in Mongoose

I have created an API using Express.js and mongoose to find users based on their ids in an array. // Here is the array of user ids const followedIds = follow.map((f) => f.followed); console.log(followedIds); // This will log [ '5ebaf673991fc60204 ...

Ways to detach event listener in Vue Component

One of my Vue2 components has a custom eventListener that I added in the mounted lifecycle hook. I am now trying to figure out the correct way to remove this listener when the component is destroyed. <template> <div> ... </di ...

Unraveling the Enigma of Event Handlers: Mastering the Organization of a Sprawling jQuery File within an AJAX

I've created a web application that heavily relies on AJAX and jQuery for DOM manipulation and making AJAX requests. However, I'm facing a problem with my JavaScript file: The issue is that my JavaScript file consists of a huge collection of eve ...

The JSON output is throwing an error because it is unable to access the property '0' since it is

Trying to convert JSON data into an HTML table, I encountered the following error: "Cannot read property '0' of undefined" <?php $idmatchs = "bGdzkiUVu,bCrAvXQpO,b4I6WYnGB,bMgwck80h"; $exploded = explode(",", $idmatchs); $count = count( ...

Error message: Unable to load image from local source in Vue application

I am currently working on creating a simple dice roll game in VueJs. However, I encountered an issue with using the dice images as it keeps giving me a 404 error. When I attempted to use require(), it stated that the function was not defined. After some t ...

The functionality of wp_script_is in WordPress seems to be malfunctioning when it comes to

I need to load a certain file only after a specific script has finished loading. Wordpress offers a useful method called 'wp_script_is' for detecting if a script has loaded or not. When I use the jquery handle with "done", it functions as expecte ...

Having trouble with Django REST API and Axios POST request not functioning properly

I'm currently working on developing a simple API that allows users to input data, submit it, and have it stored in a database. To accomplish this, I am utilizing React and Django Rest Framework. In my App.js file: const [name, setName] = useState(&ap ...

How can I activate JQUERY when an event occurs?

I am trying to create a selection box where, upon clicking an item on the left, it will shift automatically to the right. However, I am facing issues with using triggers to achieve this functionality. Here is the code I have written. <script type="te ...

Steps for generating an HTML form in a fresh window

I am currently working with this function: // open a new window. Create and submit form function createSubmitForm(response) { var external = window.open('about:blank', 'external'); var doc = external.document; var body = $( ...

Search the database to retrieve a specific value from a multi-dimensional array

My database is structured as shown in the image below: I am attempting to retrieve tasks assigned to a specific user named "Ricardo Meireles" using the code snippet below: const getTasksByEmployee = async () => { setTasks([]); const query = qu ...