Could someone assist me in streamlining code that analyzes different attributes of objects?

My current code seems to be quite bloated and I believe it can be optimized for better efficiency. The goal is to compare an array of objects that represent players, in order to determine the player with the highest majorityScore property. In cases where there are multiple players with the same high score, a comparison of their factions using a priorityMap will determine the ultimate winner.

players = [
  {
    majorityScore: 4,
    faction: 'AR'
  },
  {
    majorityScore: 8,
    faction: 'MOU'
  },
  {
    majorityScore: 2,
    faction: 'MOB'
  },
  {
    majorityScore: 8,
    faction: 'I'
  }
];

const priorityMap = {
  'MOB': 1,
  'I': 2,
  'MOU': 3,
  'AR': 4,
  'S' : 0
}

let winner;
let highScore = -1;
let duplicates = [];
for(let i = 0; i < players.length; i++){
  if(players[i].majorityScore > highScore){
    highScore = players[i].majorityScore;
    winner = players[i]
    duplicates = [winner];
  } else if (players[i].majorityScore === highScore){
    duplicates.push(players[i]);
  };
}
if(duplicates.length > 1){
  let highFactionScore = duplicates.reduce((a,v) => {
    if(priorityMap[v.faction] > a){
      a = priorityMap[v.faction];
    }
    return a;
  }, 0);
  let winningFaction = Object.keys(priorityMap).find((k) => {
    return priorityMap[k] === highFactionScore;
  });
  winner = duplicates.filter((v) => {
    return v.faction === winningFaction
  })
}

Answer №1

If you are looking to condense an array of objects into a single object, consider utilizing the reduce method in JavaScript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Instead of only checking factions after identifying players with the highest majority score, it can be beneficial to assess factions whenever comparing players who share the same majority score.

let champion = players.reduce((accumulator, currentValue) => {
    if (accumulator.majorityScore < currentValue.majorityScore) {
        return currentValue;
    } else if (accumulator.majorityScore > currentValue.majorityScore) {
        return accumulator;
    } else {
        return priorityMap[accumulator.faction] > priorityMap[currentValue.faction] ? accumulator : currentValue
    }
});

Answer №2

Here is a concise approach using a temporary object to maintain a score-based dictionary. The method involves updating the score property with the value from priorityMap[faction] while iterating through the array of players.

const players=[{majorityScore:4,faction:"AR"},{majorityScore:8,faction:"MOU"},{majorityScore:8,faction:"MOU12"},{majorityScore:8,faction:"MOU20"},{majorityScore:2,faction:"MOB"},{majorityScore:2,faction:"MOB2"},{majorityScore:8,faction:"I"}],priorityMap={MOB:1,I:2,MOU:3,MOB2:4,AR:4,S:0,MOU12:21,MOU20:22};

function getGroups(arr) {

  const temp = {};

  return arr.reduce((acc, c) => {
    const { majorityScore: score, faction } = c;

    acc[score] = (acc[score] || { majorityScore: score, faction });

    if (priorityMap[faction] > temp[score]) {
      acc[score].faction = faction;
    }

    temp[score] = priorityMap[faction];

    return acc;
  }, {});
}

console.log(getGroups(players));

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

Loop through the mongoose object using EJS

When I insert <%= products %> into my view, it displays [Object Object], indicating that the mongoose resultset is an object. However, when I attempt to iterate over the products object, I receive an error stating products.forEach is not a function. ...

Creating an uncomplicated selector bar for a basic javascript slideshow

I've spent the last couple of hours teaching myself some basic JavaScript, so please bear with me. Currently, I have a simple code in place for a straightforward slideshow on a website. Here is the JavaScript I'm using (where the 'slide&apo ...

Combining two sets of JSON data through mathematical operations

Two JSON files are available: one containing team names and codes, and the other with match details and scores. The goal is to create another JSON file that aggregates total matches won-lost and total goals. The JSON files are located at: JSON 1 ...

Creating an array of objects in C++ using the new keyword and initializer values

I created a sample class that looks like this: class cls{ public: cls(int a):value(a){} private: int value; }; My goal is to dynamically create an array with each element initialized to a specific value, such as 2: cls *arr = new cls[N](2); How ...

Ensuring child input components are validated upon submission using Vee-Validate and Vue.js 2

Currently, I am working on creating a Registration form with multiple "Input Field" components that require validation once the Submit button is pressed. While each input field validates individually when the text is changed, I am struggling to implement a ...

creating an array of nested structures

Why am I receiving an error message from my compiler stating that there are too many initializer values when I try to initialize this nested structure array? Is there an alternative approach I can take to solve this issue, or could someone please point o ...

Creating a distinctive appearance for JavaScript's default dialogue box

Is there a way to enhance the design of my code that prompts the user for input using JavaScript's `prompt`? Currently, it appears too simplistic. Are there any CSS or alternative methods to improve its appearance? function textPrompt(){ var text = ...

Adjusting an image size using JQuery after resizing a canvas will only resize the image itself, not

How can I resize an image within a canvas using JQuery in a way that only the image is resized, not the entire canvas? function resizeImage(width, height){ var image = document.getElementById('resizeImage'), canvas = document.createEleme ...

Utilizing the child's property of an object in Three.js beyond the loader.load function

I am looking for a way to dynamically update the color property of an object using dat.GUI(). It is straightforward when working with objects created using three.js geometry. However, I am facing some challenges as I am working with imported objects (.obj ...

How can I customize ngx-quill editor's link behavior to open in the same tab instead of a new tab?

Incorporating Quill's rich editor with Angular 4 leads to the issue of links being automatically set to open in a new tab due to "_target = "blank". Is there a way to have the links open in the same tab instead? Any guidance on this matter would be gr ...

Panning or dragging on Google Map V3 can become unresponsive when the cursor moves outside of the map element

I have incorporated a Google map in a specific section of my webpage. I am facing an issue where if I click and drag the mouse outside the map area to other div elements, releasing the mouse still causes dragging/panning to continue when I return to the m ...

Create a cookie in javascript

There seems to be an issue with this code snippet: function getCookie(c_name) { var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0;i<ARRcookies.length;i++) { x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y=ARRcookies[i].substr(ARRc ...

Tips for integrating PHP into a Bootstrap modal dialog

After discovering and modifying a php script designed to process contact form content and display alerts on a Bootstrap 3 modal window, I encountered some issues. While I was able to successfully display errors and show the modal onload without any php con ...

Steps for implementing drag-and-drop feature for a div in a template

I am looking to implement draggable functionality on a div element dynamically. The unique id for the div is generated using the code snippet below: var Exp=0; view.renderFunction = function(id1){ var id= id1 + Exp++; $("#"+id).draggable(); }; In my ...

Angular allows users to interact with objects in THREE.js by simply clicking on

I've tried numerous solutions, but none of them seem to work - the cube is in the wrong position and only one face is detected. Since the angular event is easy to call. 1. Insert a tag into the HTML code. <div (click)="onClickCanvas($event)"> ...

When a user clicks on buttons other than the submit button, the input field redirects to another page

A helpful user named Vittore assisted me in displaying the first 5 list items of the unordered list and implementing page navigation with next and previous buttons flawlessly. The issue arises with an input field, which functions correctly by navigating ...

How can an ESM-only package be included using the require method?

My current situation involves a node dependency that was previously included in version 2 using require. However, with the release of version 3, the library can now only be included with import. I encountered the following error: [ERR_REQUIRE_ESM]: requi ...

Error in HTML5 video: Unable to access property '0' as it is undefined

I am trying to create a simple block displaying an HTML5 video tag. I want the ability to play different videos along with their titles from a JSON file by using previous and next buttons. Clicking the next button should play the next video, and the same g ...

A "TypeError" occurred because the property "$on" of undefined was unable to be read in the q-ajax-bar

Quasar Version: v0.17.2 Node Version: v9.4.0 NPM Version: 5.6.0 While working on my project, I am trying to manipulate the ajax bar using start/stop events. However, an error occurs when my App.vue file is being rendered. Error Message in mounted hoo ...

Convert the JSON data received from a jQuery AJAX call into a visually appealing HTML table

Utilizing AJAX as the action, I have created a search form. In the success of the AJAX request, I am seeking a way to update a specific div without refreshing the entire page. Below is my form: <?php $properties = array('id' => &ap ...