JavaScript: altering an array of objects

I have an array that looks like this:

data = [
  {name:'Tom', a:1, b:1, c:0},
  {name:'Sam', a:0, b:1, c:1},
  {name:'Tom', a:0, b:0, c:1},
  {name:'Sam', a:1, b:2, c:1},
  {name: 'Jack', a:1, b:2, c:0}
]

My goal is to calculate the total for each property of objects with the same name and then remove any duplicates:

result = [
  {name:'Tom', a:1, b:1, c:1},
  {name:'Sam', a:1, b:3, c:2},
  {name: 'Jack', a:1, b:2, c:0}
]

Is there a way to achieve this using only pure JavaScript?

Answer №1

Algorithm proposal to categorize random attributes using a hash table.

let data = [{ name: 'Anna', x: 1, y: 1, z: 0 }, { name: 'Ben', x: 0, y: 1, z: 1 }, { name: 'Anna', x: 0, y: 0, z: 1 }, { name: 'Ben', x: 1, y: 2, z: 1 }, { name: 'Charlie', x: 1, y: 2, z: 0 }],
    categorizedData = [];

data.forEach(function (item) {
    if (!this[item.name]) {
        this[item.name] = { name: item.name };
        categorizedData.push(this[item.name]);
    }
    Object.keys(item).forEach(function (key) {
        if (key !== 'name') {
            this[key] = (this[key] || 0) + item[key];
        }
    }, this[item.name]);
}, Object.create(null));

console.log(categorizedData);

Answer №2

Implement a solution using a for loop in conjunction with Array#splice and an object for index referencing.

// Utilizing an object for index referencing
var obj = {},
  dc = 0,
  len = arr.length;

// Loop through the array of objects
for (var i = 0; i < len; i++) {
  var v = arr[i - dc];
  if (obj.hasOwnProperty(v.name)) {
    arr[obj[v.name]].a += v.a;
    arr[obj[v.name]].b += v.b;
    arr[obj[v.name]].c += v.c;

    arr.splice(i - dc++, 1);
  } else {
    obj[v.name] = i - dc;
  }
}

var arr = [{
  name: 'Tom',
  a: 1,
  b: 1,
  c: 0
}, {
  name: 'Sam',
  a: 0,
  b: 1,
  c: 1
}, {
  name: 'Tom',
  a: 0,
  b: 0,
  c: 1
}, {
  name: 'Sam',
  a: 1,
  b: 2,
  c: 1
}, {
  name: 'Jack',
  a: 1,
  b: 2,
  c: 0
}];

var obj = {},
  dc = 0,
  len = arr.length;

for (var i = 0; i < len; i++) {
  var v = arr[i - dc];
  if (obj.hasOwnProperty(v.name)) {
    arr[obj[v.name]].a += v.a;
    arr[obj[v.name]].b += v.b;
    arr[obj[v.name]].c += v.c;
    arr.splice(i - dc++, 1);
  } else {
    obj[v.name] = i - dc;
  }
}

console.log(arr);

Answer №3

To enhance your data structure, establish a secondary array. Next, go through each element in the initial array and compute the sum of its properties. Store these sums in the new array while removing any duplicates from the original array. Voila!

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

Unable to insert rows into an array using sqlite3 in Node.js

I have a snippet of Node.js code that queries a SQLite Database and prints each row individually. The original code is as follows: var sqlite3=require('sqlite3').verbose(); var db=new sqlite3.Database('./database.db',(err)=>{ i ...

When using AutoComplete in MUI, I encountered an issue while attempting to assign a default value to the checkbox from an API. Instead of achieving the desired result, I received an error stating "(inter

Within this snippet, I am seeking to retrieve a default value from the API to populate a checkbox initially. I have employed the Material-UI Autocomplete component, which includes a defaultValue prop. Despite my efforts to utilize this prop, I am encounter ...

Vue.js's @click feature can be enhanced with ternary operations

I've been attempting to achieve the following in Vue.js, but I keep encountering an error that says [plugin:vite:vue] Unexpected token (1:27): @click="selectedFiles.push(file.id); selectedFiles.length < 1 ? isCollapse=false: isCollapse=true&q ...

Error messages cannot be custom in production when reading a 409 response JSON from the server

After setting up my asp.net core MVC server, I decided to implement better error handling. However, upon deploying the changes to the production environment, I noticed a discrepancy in how my server responds to 4xx errors. While everything works fine on m ...

Issues with Google maps are causing multiple maps to malfunction

After incorporating some jquery code to create multiple maps upon window load, I noticed a peculiar issue with the maps - they all display the same location despite having different latitudes and longitudes set. Upon inspecting the code responsible for cr ...

Tips for dynamically modifying the default keyword in a div using Jquery to apply color

I am attempting to dynamically apply colors to default SQL keywords. For example, when a user enters the words "select * from table" in a div, I want the words select, from, and table to be displayed in blue color while the remaining default words are di ...

Exploring methods to conduct testing on an AngularJS application using AngularJS end-to-end testing, specifically focusing on scenarios involving multiple inputs

Our program includes a directive that is repeated multiple times with an input field. The structure of our code resembles the following: <li> <label>AMI</label> <div class="searchbox" searchbox="" filter="search.ami"> ...

The AdminLTE Bootstrap Table Search Bar vanishes when extra <th> tags are added

Currently facing difficulties with the table functionality in AdminLTE. By default, AdminLTE includes a search and organization feature in its table structure. When I insert some table data using PHP, everything looks fine. However, when I attempt to add ...

`Simple HTML DOM is failing to recognize duplicate values in arrays`

Currently, I am utilizing Simple HTML DOM in the following manner: foreach($html->find('img', 18) as $d) { echo $d->outertext; } My goal now is to incorporate an array of variables, specifically images. To achieve this, I have made the f ...

I am having trouble resolving 'otp-input-react' in my project directory at D:projectappsrc

I have been troubleshooting this issue but haven't been able to find a solution yet. I even tried uninstalling and reinstalling the package, but it still isn't working as expected. Here are some images for better clarity: https://i.stack.imgur.c ...

Is there a method to verify information stored within an ArrayList?

I am facing an issue where I need to develop a small game that requires me to create a window similar to the one shown in the image below: https://i.sstatic.net/LCJKK.png The main requirement of the program is to ensure that the words are taken from a pr ...

Dynamic starting point iteration in javascript

I'm currently working on a logic that involves looping and logging custom starting point indexes based on specific conditions. For instance, if the current index is not 0, the count will increment. Here is a sample array data: const data = [ { ...

Using the className prop in a React Component

Struggling to assign a classname to the material-ui Button component. Here are my failed attempts: Attempt 1: attributes.map((attribute, index) => { const classString = 'classes.button' + index; console.log(classString) return ( &l ...

The getServerSideProps function in Next.js is only executed once, meaning it won't retrieve fresh data when accessed via next/router

I'm working on a Next.js application with Server-Side Rendering (SSR) where I have an async function called getServerSideProps that is exported like this: export const getServerSideProps = getGenericServerSideProps([""]); The getGenericServerSideProp ...

What is the fewest amount of commands needed to generate a client-side Javascript code that is ready for use?

In the realm of JavaScript libraries found on Github, it has become increasingly challenging to integrate them directly into client-side projects with a simple script tag: <script src="thelibrary.js"></script> The issue arises from the browse ...

How can you modify the starting point of data in jQuery flot?

Currently using Flot to create a graph displaying clicks per minute within the first 60 minutes of short URLs generated at . The graph currently displays data from minute 0 to minute 59. My query is about adjusting the data to start at 1 and end at 59, wh ...

When using Vuetify's v-text-field with the type "number", remember to assign a null value instead of an empty string

One issue I've encountered is that when using v-text-field with the type="number" attribute, the value is set to an empty string after manual clearing. Ideally, I would like it to return null in such instances. Is there a way to set an attr ...

Change the page using JavaScript after submission

I am currently working on incorporating Firebase authentication into a Node.js Express-based application. However, I have encountered the following error: nexttick.js:45 Uncaught TypeError: Cannot read property 'redirect' of undefined This ...

Ways to verify an NPM package for non-JavaScript code

How can we determine if an npm package consists purely of JavaScript without any bindings or dependencies that require compiling? For instance, the node-speaker package (https://github.com/TooTallNate/node-speaker) requires compilation (mpg321), while req ...

Accessing Google Analytics with a single OAuth token using the JavaScript API: A step-by-step guide

I'm currently developing a webpage for exclusive users to view shared Google Analytics data. I have managed to obtain an OAuth token for the account housing this data using JavaScript, but sadly it expires in just 1 hour. Is there a way to utilize th ...