Tips for minimizing a collection of objects?

Currently, I am working on developing a unique quiz format where there are no correct or incorrect answers; instead, responses are given a score ranging from 1 to 4.

Each question falls under one of four distinct categories (such as cat, dog, rabbit, alpaca). The user's response for each question is recorded in an array with the corresponding category like so:

answersChosen = [
    {key: 'cat', value: 4},
    {key: 'dog', value: 2},
    {key: 'rabbit', value: 1},
    {key: 'alpaca', value: 3},
    {key: 'cat', value: 1},
    {key: 'dog', value: 4},
    {key: 'rabbit', value: 1},
    {key: 'alpaca', value: 2},
    {key: 'cat', value: 2},
    {key: 'dog', value: 1},
    {key: 'rabbit', value: 4},
    {key: 'alpaca', value: 3},
    {key: 'cat', value: 3},
    {key: 'dog', value: 4},
    {key: 'rabbit', value: 1},
    {key: 'alpaca', value: 2},
];

I am currently exploring ways to condense the array into the four categories with an aggregated score representing each category to identify the most common animal. In this scenario, it would be a dog:

//Updated array
results = [
    {key: 'cat', value: 10},
    {key: 'dog', value: 11}, //top score
    {key: 'rabbit', value: 7},
    {key: 'alpaca', value: 10},
];

Answer №1

For a clever solution, utilize the reduce method to map keys from each element in an object and add their values to the respective key.

let answersChosen = [{key: 'cat', value: 4},{key: 'dog', value: 2},{key: 'rabbit', value: 1},{key: 'alpaca', value: 3},{key: 'cat', value: 1},{key: 'dog', value: 4},{key: 'rabbit', value: 1},{key: 'alpaca', value: 2},{key: 'cat', value: 2},{key: 'dog', value: 1},{key: 'rabbit', value: 4},{key: 'alpaca', value: 3},{key: 'cat', value: 3},{key: 'dog', value: 4},{key: 'rabbit', value: 1},{key: 'alpaca', value: 2},];

let reduced = answersChosen.reduce((op,{key,value}) => {
  op[key] = op[key] || {key,value:0}
  op[key].value+= value
  return op
}{})

console.log(Object.values(reduced))

Answer №2

This method takes a unique approach by utilizing a Map to construct the desired result set in a separate step.

To determine the highest score, you can use array reduction to retrieve the object with the maximum values.

var answersChosen = [{ key: 'cat', value: 4 }, { key: 'dog', value: 2 }, { key: 'rabbit', value: 1 }, { key: 'alpaca', value: 3 }, { key: 'cat', value: 1 }, { key: 'dog', value: 4 }, { key: 'rabbit', value: 1 }, { key: 'alpaca', value: 2 }, { key: 'cat', value: 2 }, { key: 'dog', value: 1 }, { key: 'rabbit', value: 4 }, { key: 'alpaca', value: 3 }, { key: 'cat', value: 3 }, { key: 'dog', value: 4 }, { key: 'rabbit', value: 1 }, { key: 'alpaca', value: 2 }],
    sums = Array.from(
        answersChosen.reduce((map, { key, value }) => map.set(key, (map.get(key) || 0) + value), new Map),
        ([key, value]) => ({ key, value })
    ),
    max = sums.reduce((r, o) => {
       if (!r.length || r[0].value < o.value) return [o];
       if (r[0].value === o.value) r.push(o);
       return r;
    }, []);

console.log(sums);
console.log(max);
.as-console-wrapper { max-height: 100% !important; top: 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

Trouble encountered with bootstrap toggling when multiple identical inputs are used

Problem with Bootstrap toggle not working on multiple identical inputs unless the first input is pressed. Even then, not all inputs are checked/unchecked. I've created a small example I want to ensure that when one input is toggled, all others have ...

Enhancing a Given Interface with TypeScript Generics

I am looking to implement generics in an Angular service so that users can input an array of any interface/class/type they desire, with the stipulation that the type must extend an interface provided by the service. It may sound complex, but here's a ...

Encountering a problem with Webpack SASS build where all files compile successfully, only to be followed by a JavaScript

Being a newcomer to webpack, I am currently using it to package an Angular 2 web application. However, I am encountering errors related to SASS compilation and the ExtractTextPlugin while working on my project. Here is a snippet from my webpack configurat ...

My goal is to create a comprehensive collection of stories showcasing all Material UI components in React

Looking for a way to efficiently import all MUI components stories into my storybook. Is there a tool or repository available that can automate the generation of these stories, or perhaps has pre-written stories for all MUI components? I attempted to cre ...

Issue with modal-embedded React text input not functioning properly

I have designed a custom modal that displays a child element function MyModal({ children, setShow, }: { children: JSX.Element; setShow: (data: boolean) => void; }) { return ( <div className="absolute top-0 w-full h-screen fle ...

Unable to receive any response with AJAX requests

Welcome to my HTML page <html> <head> <title>Using AJAX</title> </head> <script type="text/javascript" src="ajax.js"></script> <body> <form action="searchItems.php" name="searchItem" method="p ...

Concealing the div during the initial page load

person.jsp <script type="text/javascript"> function validateadvance() { document.getElementById("fn").style.visibility = "visible"; } $(function() { $(".dp").datepicker(); }); </s ...

Triggering an event upon selecting a dropdown option

I'm currently working on a form that includes a dropdown menu. My goal is to display specific keywords for each trip when selected from the menu (preferably below the input field, as shown in the code snippet below). .show has been set to display:non ...

I'm facing a challenge with discord.js where I can't seem to get multiple prefixes to work. Do you have any suggestions on how I can modify it to

As the title suggests, I've been experimenting with different versions of the code below. The current version can recognize firstPrefix but not secondPrefix. I simply want my discord bot to be able to identify both prefixes and split the Args accordin ...

How can I incorporate multiple graphs into my AmCharts display?

I am new to using amcharts and have successfully implemented a code snippet to generate two graphs in a chart. The charts are loaded from an external data source specified in the code. var chart = AmCharts.makeChart("chartdiv", { "type": "serial", "d ...

Discovering and choosing the appropriate course

I am facing a situation where I need to specifically select an element with the class .foo, but there are two anchor tags, both having the class .foo. However, I only want to select the one without the additional .bar class. How can I achieve this? <a ...

What is the best way to update an array of string values with corresponding IDs from a different table

data set 1: ID Array 100 ["a","c","b"] 200 ["d","e","c","a"] data set 2: Letter ID a 1 b 2 c 3 d 4 e 5 Desired output: ID ID_Array 100 [1,3,2] 200 [ ...

Can the use of setTimeout alter global variables?

let currentVariable = 'ye'; setTimeout(()=>{ currentVariable = 'lin' },2000) Hey everyone, I have a question. Initially, I set a variable currentVariable to "ye", and then in a setTimeout function I change it to "lin" after 2 s ...

Initiate a fresh start with an automatic input reset

When you perform an action in the first id = "benodigheden", I believe there should be a specific outcome that then triggers a second rule for id = "benodigheden". However, I have been unsuccessful in finding information on this topic online. It seems like ...

Suspend features for moving between pages in history

In the application, we have two main pages - Home.vue and Statistics.vue. The Home.vue page renders the TableFields.vue component. On the Home page, there are fields with numbers that have an initial value of "3" set upon page load. An interval running a c ...

The formio onchange event may result in an undefined object

Encountering an issue here: Error: src/app/app.component.html:1:30 - error TS2532: Object is possibly 'undefined'. 1 <form-builder [form]="form" (change)="onChange($event)"></form-builder> while working on my for ...

The required module does not have a default export available when using express routing

I could really use some help figuring out what I'm missing here. Just to provide some context, my app is built on node.js (version 16.13.1) using the latest version of express and a nginx reverse proxy. app.mjs import router from './assets/js/r ...

Exploring the process of searching for an id within an array of objects received through axios in Vue 2

I am currently working on verifying whether the user is included in the list that I retrieve using axios. However, I am facing an issue where the FILTER option I have used consistently returns undefined or [], even when the user does exist in the array. A ...

What is the best way to sequentially invoke methods in Angular?

When initializing in the ngOnInit() method, I need to call several methods synchronously. However, all these methods involve asynchronous calls to an API. The challenge is that certain variables must be set before proceeding with the subsequent methods. Un ...

The backspace key is unresponsive following the use of a jQuery class

Using a specific class for an input field: Here is the code for the input field: <?php echo $this->Form->input('duration', array('class'=>'input-large text-right number-field','value'=>'0&apo ...