Looking to categorize and sum the values within an array of objects using JavaScript?

I'm looking to optimize this response data within my Angular application.

res=[
{  "url": "/page1", "views": 2 },
{  "url": "/page2", "views": 1 },
{  "url": "/page1", "views": 10 },
{  "url": "/page2", "views": 4 },
{  "url": "/page3", "views": 1 },
{  "url": "/page2", "views": 0 },
{  "url": "/page3", "views": 14 },
{  "url": "/page1", "views": 04 },
{  "url": "/page3", "views": 14 },
]

I aim to transform the response into:

res=[
{  "url": "/page1", "views": 104 },
{  "url": "/page2", "views": 104 },
{  "url": "/page3", "views": 104 },
]

Answer №1

Utilize Array's reduce() method

var finalResult = data.reduce((accumulator, object) => {
       accumulator[object.url] = (accumulator[object.url] || 0) + object.views;
       return accumulator;
    },
    {}
);

Result displayed in node CLI:

> var finalResult = data.reduce((accumulator, object) => { accumulator[object.url] = (accumulator[object.url] || 0) + object.views; return accumulator; }, {});
undefined
> finalResult
{ '/page1': 16, '/page2': 5, '/page3': 29 }

Answer №2

To simplify the code, you can utilize a basic reduce operation:

 

var data = [
{  "url": "/page1", "views": 2 },
{  "url": "/page2", "views": 1 },
{  "url": "/page1", "views": 10 },
{  "url": "/page2", "views": 4 },
{  "url": "/page3", "views": 1 },
{  "url": "/page2", "views": 0 },
{  "url": "/page3", "views": 14 },
{  "url": "/page1", "views": 04 },
{  "url": "/page3", "views": 14 },
];

data = data.reduce((value, accumulator) => {
if (accumulator.some(entry => entry.url == value.url)) {
    accumulator.find(entry => entry.url == value.url).views += value.views;
} else {
    accumulator.push({
        url: value.url,
        views: value.views,
    });
}
return accumulator;
}, []);

console.log(data);

Answer №3

The solution provided gives back an object as the output. To achieve this, you can utilize the reduce method like demonstrated below:

const res=[{"url":"/page1","views":2},{"url":"/page2","views":1},{"url":"/page1","views":10},{"url":"/page2","views":4},{"url":"/page3","views":1},{"url":"/page2","views":0},{"url":"/page3","views":14},{"url":"/page1","views":04},{"url":"/page3","views":14}],
  
merged = res.reduce((acc,{url,views})=> {
    acc[url] = acc[url] || {url, views:0}
    acc[url].views += views;
    return acc;
}, {}),

output = Object.values(merged)
console.log(output)

Below is a more concise version of the code snippet above:

const res=[{"url":"/page1","views":2},{"url":"/page2","views":1},{"url":"/page1","views":10},{"url":"/page2","views":4},{"url":"/page3","views":1},{"url":"/page2","views":0},{"url":"/page3","views":14},{"url":"/page1","views":04},{"url":"/page3","views":14}],

output = res.reduce((acc,{url,views})=>
    ((acc[url] = acc[url] || {url, views:0})["views"] += views, acc), {})
console.log(Object.values(output))

Another alternative approach involves using Map

const res=[{"url":"/page1","views":2},{"url":"/page2","views":1},{"url":"/page1","views":10},{"url":"/page2","views":4},{"url":"/page3","views":1},{"url":"/page2","views":0},{"url":"/page3","views":14},{"url":"/page1","views":04},{"url":"/page3","views":14}],

map = res.reduce((m,{url,views})=> {
    const o = m.get(url) || {url,views:0};
    o.views += views;
    return m.set(url, o);
}, new Map),

output = [...map.values()];
console.log(output)

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

Non-IIFE Modules

Check out this discussion on Data dependency in module I have several modules in my application that rely on data retrieved from the server. Instead of implementing them as Immediately Invoked Function Expressions (IIFEs) like traditional module patterns ...

Tips for assigning unique non-changing keys to siblings in React components

I've been searching for a solution for more than an hour without success. The structure of the data is as follows: const arr = [ { id: 1, title: 'something', tags: ['first', 'second', 'third'] }, { id: 2, t ...

Ways to extract repeated value from a function?

Currently, I am working with two files. One file contains a script that generates a token, while the other file handles that token. The issue arises with the second script, as it only logs the initial token received and does not update with any new values ...

Tips for pinpointing parent elements within a group of various sub child elements

CSS - <div class="windows" id="window'+divCount+'"> <p id="windowName'+divCount+'"></p> <p id="para'+divCount+'">Source</p> </div> <div cla ...

Ways to reset a dropdown selection when a switch is turned off

Hey there! I'm facing a bit of a challenge while working on my project using React, TypeScript, Ant Design, and Refine Framework. In my edit.tsx page component, I need to modify a record based on the value of catHasParent fetched from the database. Wh ...

Tips for dynamically displaying images in both horizontal and vertical orientations

I would like to showcase images in the imageList. Here is what I want: AB CD How can this be achieved? It's not a matter of being even or odd Perhaps the list could look something like this: ABCDE FG I simply want a new row or display:block when ...

Tips for creating a mock for a function that yields a JSX Element

I am facing a problem where I have a function that returns a JSX Element. Here is a snippet of the code: myFunction.jsx const myFunction = (props) => { // ... do something with props return <MyElement {...newProps} /> } // MyElement.j ...

Execute Yarn commands from the main directory

In the midst of my project, I have various sub projects - one of which is dedicated to JavaScript. My intention is to employ this JavaScript project as a task runner for the entire endeavor using gulp. However, I've hit a snag in the process. The lay ...

Change the <base> element programmatically during server-side rendering

Searching for a way to obtain the base URL for an HTML page, so that relative URL requests from the browser utilize that base. If you are looking for answers, check out this link: Defining root of HTML in a folder within the site root folder When serving ...

The post request fails to send certain variables

I'm experiencing an issue with a form that has rows structured like this: <div class="row unit" onmouseover="this.style.background = '#eeeeee';" onmouseout="this.style.background = 'white';" onclick="if(event.srcElement.nodeNam ...

Error: The bun.js application encountered a SegmentationFault at line 188

I'm attempting to execute the following command on my current repository, which already has a registry set up in the .npmrc. bun install -y The purpose of the -y flag is to generate the yarn v1 lockfile. However, it's resulting in the followin ...

Encountering an issue with the for loop in React Native when using FlatList

As a beginner in programming, I am eager to dynamically render a list. The Navbar parent component holds the state with different Food Types categories such as Mexican and Chinese, each with its corresponding menu. My goal is to display each Food Type fol ...

display different vue component based on screen size

I am in search of a method to implement responsive components in Vue.js (Nuxt). I have developed this mix-in but encountering an error: export const mediaQuery = { data() { return { breakpoints: { sm: 576, md: 768, lg: ...

JavaScript encountered an issue while parsing XML: the format is not well-formed

I keep seeing an error message saying "Error parsing XML: not well-formed" when I encounter this line in my javascript code: for (var i=1; i<=totalImgs; i++) If I remove the < character from the line, the parsing error goes away. However, the javas ...

What could be causing my webpage to freeze every time a filter button is selected?

Tasked with developing a webpage similar to Pinterest by utilizing data from a JSON response. Each JSON object contains a service_name key, which can be manual, twitter, or instagram. I made an effort to implement three filter buttons to only display the r ...

Ensure that the flex item spans the entire width of the page

I'm struggling to make my audio-player resize properly to fit the full width of my page. I can't seem to figure out what I'm missing or doing wrong... (Current Look) I'm attempting to utilize HTML custom controls to design my JSON Aud ...

Using hooks for conditional rendering

Background Information : My current project involves creating a form using hooks and rendering components based on the step. Challenge Encountered : I received this error message: "Error: UserFormHooks(...): Nothing was returned from render. This usually ...

Tips for avoiding HTML <tags> in the document.write function

I am trying to paint the actual HTML code within a tag using JavaScript but escaping it doesn't seem to be working. function displayHTMLString(n){ document.write("'<table>'"); for (i in range(0,n)){ ...

Should I use YUICompressor or a comparable tool in PHP?

After using yuicompressor.jar for quick JavaScript minimisation on my test server, I ran into issues when deploying to my public server due to server restrictions on java execution. This means I need to find an alternative solution for on-the-fly JS compre ...

Updating An Angular Application from version 11 to version 12 Challenge

Once I completed installing all the required dependencies as per: https://update.angular.io/ I executed the command 'ng serve' in the terminal and encountered the following errors: ./node_modules/leaflet/dist/images/marker-icon.png:1:0 - Error: ...