Sum Variables within a JavaScript Array

Hey there! I'm working with a JavaScript array that looks a little something like this.

{x: red, y: 2}
{x: blue, y: 3}
{x: blue, y; 4}
{x: green, y: 5}

I'm wondering how to combine the duplicate values so that my array ends up looking like the code snippet below.

Is it possible to achieve this using a loop? I have a large amount of data that needs to be formatted in the same way.

{x: red, y: 2}
{x: blue, y: 7} #the two blue y variables have been added
{x: green, y: 5}

Answer №1

Here is a suggestion:

var newArr = [];

const data=[{x:"red",y:2},{x:"blue",y:3},{x:"blue",y:4},{x:"green",y:5}];

var uniqueX = []
data.forEach((element) => {
  if (!newArr.includes(element.x)) { 
    uniqueX.push(element); 
    newArr.push(element.x);
  } else { 
    uniqueX.forEach(item => item.y += item.x == element.x ? element.y : 0);
  }
})

console.log(uniqueX);

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

How can we prevent the filter string in Asp.Net Core OData from overwriting the passed text?

My query using odata looks like this: http://localhost:5000/odata/Levels?$filter=contains(Code, '+14') However, when the query reaches my controller, I notice that the filter object received is altered to be: {contains(Code, ' 14')} T ...

Angular HttpClient not recognizing hashtag

I'm trying to make a REST API call, but running into issues with the developerId parameter being sent incorrectly: let developerId = "123#212"; let url = \`\${Constants.BASE_URL}\${marketId}/developers/\${developerId}\`; retur ...

Display the output from a JavaScript code snippet on the console

Is there a simple way to incorporate JavaScript into RMarkdown and display the results in the knitted document without adding a lot of extra code? I discovered that I can create new div elements and attach them to the document's DOM, but this method s ...

User interface design for node.js and jquery web applications

When using node.js for web applications, is there a preferred UI framework to pair with it? Or is this an independent consideration? While jQuery is popular, is jQuery UI the most commonly used UI framework with the jQuery engine? Ar ...

Guide on incorporating a displacement map into a vertex shader in ThreeJS

I am a beginner in ThreeJS and I am attempting to create a asteroids-like scene with textures made of particles, similar to what is showcased on this website . However, my attempt to apply a displacement map to a points material was unsuccessful. How can ...

Guide on incorporating texture atlas in Three.js (r65)

With the recent release of the new threejs revision (r65), the uvOffset and uvScale have been relocated to texture.offset and texture.repeate. However, I am facing an issue with the texture.offset not working as intended. My goal is to showcase multiple s ...

Troubleshooting automatic login problem in VB 2013 settings

For my application, I am utilizing the most recent version of Awesomium's WebControl. The goal is for it to automatically log in when it reaches "accounts.google.com/ServiceLogin" by executing some Javascript. In my.settings.java file, I have the foll ...

Tips for retrieving the third element from a JSON array using JMeter

Can someone help me extract the third time element from the JSON array provided below? [ { "userId": 1, "id": 1, "title": " How to Shape of Character Design", "write": &q ...

Using Python Selenium to interact with elements on a web browser and make edits

Is there a way to modify an element in a web browser using Python 2.7 Selenium? Consider this element: <span id="some-random-number">100</span> While you can retrieve the text with: driver.find_element_by_id("some-random-number").text how c ...

Send functions from the back-end Node to the front-end Angular

Introduction I am currently working on a project that involves verifying email addresses within an API in order to grant users access to a restricted section. To accomplish this, I have developed backend node code with three functions built using Node and ...

Guide on merging all Vue js functions into a single js file?

As a newcomer to vue.js, I am in the process of consolidating several functions into one js file. Here is an example: example.js: function containObject(obj, list) { for (let i = 0; i < list.length; i += 1) { if (list[i] === obj) { return ...

Optimal approach for transferring numerous variables with ajax

As a newcomer to jquery, I find myself inquiring about the most efficient approach for transmitting multiple variables to php through ajax. Should I bundle them up like this: $.ajax({ data:{ input: {x: 1, y: 2} }, ... }) or should I s ...

Develop interactive, reusable custom modals using React.js

I am currently working on creating a reusable modal: Here is my component setup: class OverleyModal extends Component { constructor(props) { super(props); } openModal = () => { document.getElementById("myOverlay").style.display = "blo ...

Creating unique image control buttons for each image within a div using a combination of CSS and JavaScript

How can I create image control buttons, such as close, resize, and rotate, for each individual image when hovering over it? Each image is contained within a draggable div. I want to display an image control button next to each image. This button should on ...

Three.js WebGL shader compilation error

I am currently new to webgl and learning shaders. My current project involves wrapping a texture around a sphere to create an earth globe image. However, I have encountered issues with the fragments and vertex GLSL code. The error I am facing occurs when ...

Using a CSS button to activate a JavaScript function: A step-by-step guide

My current project involves writing a script to change the color of text when a specific button is clicked. The idea is that clicking the "Change color1" button triggers the text color change using the following code snippet: <button onclick="myFunction ...

Revising Next.js App Components Following User Authentication

I am in the process of integrating a user-based system into my static 2-page Next.js app. To handle authentication, I have chosen Auth0. My main objective is to allow users to view documents they have saved on the app, similar to Grammarly. However, I am f ...

Issue with Angular Material 2 Autocomplete: mat-option not firing keyup event

I am currently exploring methods to detect when an mat-option within the mat-autocomplete component is clicked or selected using the enter key. The click event binding functions correctly, but surprisingly the keyup.enter or solely the keyup event does no ...

Guide on integrating HTML from a response into the render function in React JS

I've been doing some research but I'm struggling to find a good solution for this issue. I have a response that looks like this: "name": "another test", "description": "para hacer el aseo", &quo ...

What is the best way to turn off jQuery UI (widget) for a particular element?

Is it possible to disable the Jquery-UI selectmenu widget for a specific element in my project so that it reverts back to its native look and functionality? I have tried various solutions suggested in a Stack Overflow thread about disabling theming for a ...