Loop through an array of objects in order to identify the key that holds the highest sum of values

const repos = [
  { JavaScript: 82061, CSS: 4992, HTML: 1992 },
  { Ruby: 47816, HTML: 8638, JavaScript: 4419, CSS: 1842 },
  { CSS: 5006, JavaScript: 812, HTML: 336 },
  { Ruby: 1898 },
];

The API has responded.

Each element in the array represents a user's GitHub repository. I am interested in determining their preferred coding language based on total size of code written in that language. Other languages may also be considered.

I am seeking a function that would identify "JavaScript" as the preferred language in this scenario.

Answer №1

To begin, utilize the reduce function to obtain a single object containing the sum of all language types (refer to the `totals` object below).

Once you have this object, convert it into an array of key-value pairs using Object.entries, and then execute another reduce operation on it to determine the language with the highest line count.

const codebases = [
  { JavaScript: 82061, CSS: 4992, HTML: 1992 },
  { Ruby: 47816, HTML: 8638, JavaScript: 4419, CSS: 1842 },
  { CSS: 5006, JavaScript: 812, HTML: 336 },
  { Ruby: 1898 }
];

const totals = codebases.reduce((accumulator, obj) => {
  for (const key of Object.keys(obj)) {
    accumulator[key] = (accumulator[key] || 0) + obj[key];
  }
  return accumulator;
}, {});

const maxCount = Object.entries(totals).reduce((accumulator, obj) => obj[1] > accumulator[1] ? obj : accumulator);

console.log('most utilized language:', maxCount[0], ', total lines:', maxCount[1]);

Answer №2

Based on a variation of @David784's solution found here (don't forget to credit them!), as I have a personal aversion to using for loops within reduce functions.

const repos = [
  { JavaScript: 82061, CSS: 4992, HTML: 1992 },
  { Ruby: 47816, HTML: 8638, JavaScript: 4419, CSS: 1842 },
  { CSS: 5006, JavaScript: 812, HTML: 336 },
  { Ruby: 1898 }
];

const mergeObjects = (obj1, obj2) =>
  Object.keys(obj2).reduce(
    (acc, key) => Object.assign(acc, { [key]: (acc[key] || 0) + obj2[key] }),
    obj1
  );

const calculateTotals = (array) => array.reduce(mergeObjects, {});

const maxLanguage = Object.entries(calculateTotals(repos))
  .reduce((max, item) => item[1] > max[1] ? item : max);

console.log('Most used language:', maxLanguage[0], ', Total lines:', maxLanguage[1]);

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

If the camera position in Three.js is trapped within an if-else statement

I am working on enhancing the variability of camera positions in order to make the 3D scene more captivating. However, I am facing an issue where the camera gets stuck at -12, causing it to oscillate between 12.00 and 12.05 before finally moving beyond t ...

What is the best way to initiate an onload event from a script embedded within a jquery plugin?

Currently, I am in the process of developing a jQuery plugin. One issue that I have encountered involves a script tag being dynamically added for LivePerson.com. The script is supposed to trigger an onLoad function specified in the configuration. However, ...

Exploring the importance of defining a JSONP callback function

I am relatively new to JavaScript and struggling with an issue in my code. My code includes an Ajax request to a server, and I receive a response from it. Due to the cross-domain nature of the request, I am utilizing JSONP. $.ajax({ url: "***", c ...

What is the reason behind JavaScript objects lacking a toJSON() method?

According to information from http://www.json.org/js.html, JavaScript objects can specify how they are serialized by JSON.stringify() through the use of a toJSON() method. It is interesting to note that numbers and strings appear to have this method, but f ...

Issue with Fullcalendar's events.php causing JSON object retrieval failure

I'm attempting to send a JSON object as a response to my fullcalendar ajax request, but instead of returning the desired result, it only returns an array. Although I am relatively new to JSON and PHP, I have conducted extensive research and have yet t ...

When using Material UI TextField with input type "date", the event.target.value does not seem to be accessible

I am currently working with Material UI and React Grid from DevExtreme to build a table that includes an input field of type date. However, when I attempt to enter the date, it does not register the change in value until I reach the year field, at which po ...

The lookahead will only find a match if there are brackets present within the string

Trying to use a negative lookahead to search for a particular pattern within a single line string: /\s+(?![^[]*]).+/g Applicable to the following cases: // Case 1 a.casd-234[test='asfd asdf'] abc defg // Case 2 asf.one.two.three four fiv ...

What is the best way to incorporate modules into the client side of TypeScript projects?

I'm currently developing a TypeScript project for client-side JavaScript code. Prior to using TypeScript, I used to import a module in vanilla ES6 JavaScript like this: import * as THREE from 'https://threejs.org/build/three.module.js'; H ...

Flask app facing compatibility issues with jQuery .getJSON

I am encountering an issue with my flask application where I am attempting to send JSON data to the browser and render it. However, the line containing $.getJSON() is not executing as expected. Here is a breakdown of the relevant code: app.py from flask ...

Merge two separate Vue applications into one cohesive application

I have developed two separate Vue apps independently from each other. User Interface Admin Interface Each app has its own routes, store, configs, etc. I came across this helpful comment here which discusses treating each app as a component within a mai ...

Associating data with controller upon click event

My application displays a tab full of objects for the user to choose from by clicking on any line. Once they make their selection, I need to send specific data related to that object to the server. This is what the interface looks like: https://i.sstatic ...

Guide to adjusting column width in an XLSX worksheet using Angular4

I am trying to convert HTML into an XLSX sheet in Angular using SheetJS. However, I am encountering an issue where the width of each column is limited to 256 only, and I need to increase it. I have attempted to use ws[!cols] of ColInfo, but I am strugglin ...

I'm having trouble customizing the appearance of a Tab Panel using the TabsAPI. The panel keeps expanding in strange ways. How can I

Trying to customize the Tabs component from MUI is proving to be a challenge. The main issue I am facing currently is: Whenever I switch between tabs, they appear to expand in size mysteriously. This behavior seems to occur only on tabs with more content ...

Challenges with creating a contact form using bootstrap modal

I'm facing an issue with a bootstrap modal contact form. It works fine on all browsers except for iPad/Safari. Can anyone help me figure out what's wrong? On iPad, the modal is positioned to the right and down the page instead of in the cente ...

Using jQuery to select elements with specific innerHTML values

$('.select option:selected[innerHTML="5"]') In this case, I am attempting to choose an option that is currently selected and has innerHTML that perfectly matches a specific string (for example: "5") For reference, here is a fiddle link: http:// ...

Tips on automatically populating a textbox without the need for a button click

I am currently using the following code: <input type="text" value="<?php echo empty($this->session->store['actual_info']['actual_total_marketing_budget']) ? '' : $this->session->store['actual_info' ...

Triggering the AJAX function in the main window

My HTML webpage has a hyperlink that, when clicked, opens the same page in another window with a hash value appended to the URL using window.open. For example, the URL could look like this: http://mywebsite.com#hash=value The webpage contains a JavaScript ...

I am looking to create a side menu that will allow for dynamic class changes upon clicking

I'm looking to create a dynamic side menu that changes class on click event. My goal is to have jQuery add a class to a clicked "li" element that doesn't already have the class "active", while removing the class from other "li" elements. I want ...

Storing self-updating entities in the state of a React component

I'm unsure about a situation I have, regarding whether it's acceptable to carry out an action like this. If I store an object in the state of my component, can that object change itself without using setState? File A.js export default class A { ...

Switch back and forth between two different function loops by clicking

I have implemented two sets of functions that animate an SVG: one set runs in a vertical loop (Rightscale.verticalUp and Rightscale.verticalDown) and the other in a horizontal loop (Rightscale.horizontalUp or Rightscale.horizontalDown). On clicking the SVG ...