Organize and categorize items

I need help sorting an object displayed below. My goal is to calculate the sum of all rating properties for each object, and then sort the objects based on the highest total rating.

For instance, if the total rating for Intro 1 is 7 and for Intro 2 is 3, then Intro 1 should be listed first.

{
  'Intro 2': [
    {
      deckName: 'Test 2',
      rating: 1
    },
    {
      deckName: 'Test 2',
      rating: 2
    }
  ],
  'Intro 1': [
    {
      deckName: 'Test 1',
      rating: 3
    },
    {
      deckName: 'Test 1',
      rating: 4
    }
  ]
}

Answer №1

Your information is here

const data = {
  "Introduction 2": [
    {
      deckName: "Test 2",
      rating: 1
    },
    {
      deckName: "Test 2",
      rating: 2
    }
  ],
  "Introduction 1": [
    {
      deckName: "Test 1",
      rating: 3
    },
    {
      deckName: "Test 1",
      rating: 4
    }
  ]
};

We will convert it to an array and sort through it

const dataArr = Object.entries(data);

const sorted = dataArr.sort(
  (a, b) =>
    b[1].reduce((acc, curr) => {
      return acc + curr.rating;
    }, 0) -
    a[1].reduce((acc, curr) => {
      return acc + curr.rating;
    }, 0)
);

Lastly, we will convert the array back to an object

const obj = {};

sorted.forEach((item) => {
  obj[item[0]] = item[1];
});

Take a look at Code Sandbox for reference: https://codesandbox.io/s/sleepy-ramanujan-dwzwjm?file=/src/index.js

UPDATE
There is a more elegant solution for converting array to object in the last step

const obj = Object.fromEntries(sorted);

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

Guide on sending JSON object to Angular custom components

I have implemented a custom element in Angular 7 using the CUSTOM_ELEMENTS_SCHEMA. My app.module.ts code is as follows: export class AppModule { constructor(private injector: Injector) {} ngDoBootstrap() { this.registerCustomElements( ...

Issue with Flex property not being supported in Safari browser

.rq-search-container { position: relative; width: 100%; background: white; display: flex; flex-direction: row; align-items: flex-start; border-radius: 2px; z-index: 30; -webkit-flex: 1 0 15em; } While this code functi ...

Find elements that are not contained within an element with a specific class

Imagine having this HTML snippet: <div class="test"> <div class="class1"> <input type="text" data-required="true"/> </div> <input type="text" data-required="true"/> </div> I'm looking to select ...

Is there a C++ equivalent to the JS Array.prototype.map method?

When it comes to JavaScript, Array.prototype.map is a powerful tool for creating a new array by applying a function to each element. Consider the following example: const elements = [{ text: 'hi1' }, { text: 'hi2' }, { text: 'hihi ...

Exploring Heroes in Angular 2: Retrieving Object Information by Clicking on <li> Items

Currently, I am delving into the documentation for an angular 4 project called "Tour of Heroes" which can be found at https://angular.io/docs/ts/latest/tutorial/toh-pt2.html. <li *ngFor="let hero of heroes" (click)="onSelect(hero)">{{hero.name}}< ...

Traverse a deeply nested JSON structure

I need assistance with looping through a complex JSON object using only JavaScript. My goal is to log each item along with its properties into the console. const nested_json = { "item1":{ "name": "banana", ...

Verify if the value present in the array exists and is less than the succeeding value within the same array

In the task at hand, I am tasked with verifying whether a value entered into an input field exists in an array and is smaller than the subsequent value in the same array. The purpose of this check is to adjust the quantity of items in a shopping cart. Cor ...

Determine the precise location of a screen element with jQuery

Can anyone help me determine the precise position of an element on the current visible screen using jQuery? My element has a relative position, so the offset() function only gives me the offset within the parent. Unfortunately, I have hierarchical divs, ...

Understanding how types intersect in TypeScript

I'm currently diving into Type Relations in TypeScript. Can someone help explain what happens when we intersect the types represented by these two expressions: {a:number}[] & {b:string}[] Does this result in {a:number, b:string}[] ? Any clarificat ...

Saving data for editing on a Laravel page can be achieved by leveraging the powerful features

I have implemented my create page using vue.js. I called the vue.js file using a component. Now, for the edit page, I followed the same procedure by calling the vue component in the blade. However, I am unsure how to save data for the edit page. Can anyone ...

Utilize a loop to display the contents of an array

I am currently working on a software program that allows users to input their daily tasks. As part of this project, I am attempting to create a feature that will display a list of all the tasks once they have been added. Below is the section of code I am u ...

Utilizing shared data properties in both JavaScript and SCSS within Vue

Vue.js 2 has caught my interest, especially with the single-file component structure: <template> <h1>Hello World</h1> </template> <script> export default { name: 'hello-world', }; </script> <style s ...

Angular - Evaluating the differences between the object model and the original model value within the view

To enable a button only when the values of the 'invoice' model differ from those of the initial model, 'initModel', I am trying to detect changes in the properties of the 'invoice' model. This comparison needs to happen in th ...

The Web Browser is organizing CSS elements in an alphabetized sequence

map.css({ 'zoom': zoom, 'left': map.width()/(2*zoom) - (point[0]/100)*map.width(), 'top': map.height()/(2*zoom) - (point[1]/100)*map.height() Upon observation, it appears that Chrome adjusts the map zoom first be ...

React: Avoid the visible display of conditional rendering component fluctuations

In my current React project, I am developing a page that dynamically displays content based on the user's login status. The state variable "loggedIn" is initially set to null, and within the return statement, there is a ternary operator that determine ...

Easily adding multiple field data with the same field name into a database can be achieved using Mongoose and Node.js (specifically Express

I am new to using nodejs and exploring the creation of a project focused on generating invoices. My goal is to store product information in mongodb utilizing mongoose and express, but I'm unsure of how to proceed. Below is a snippet of my HTML code.. ...

Guide on leveraging npm start to compile ES6 React components and Foundation Sass

Following a tutorial on setting up a React project, everything seemed to be working perfectly after installation. However, I now need to incorporate Foundation as the front-end library for a website. The issue arises because the tutorial's server.js ...

Exploring the option of showcasing multiple json_encode data on a pie chart

Hey there! I'm currently utilizing Chart.js to generate a pie chart by retrieving data from the database: <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script> <script> var ctx = document.getE ...

Browser tries to interpret Javascript code as a file organization system

Encountering an issue while trying to load my website. When I open index.html in my browser, I receive a problem loading page message. This response is puzzling as it does not indicate a file loading error. Here's a snippet of the response: Firefox c ...

Enabling ng-disabled within an ng-repeat loop

I'm facing an issue with a form that is nested inside an ng-repeat directive. The form should only be enabled if a specific field (in this case a select dropdown) is selected, but for some reason, it's not working as expected. Can anyone provide ...