Calculate the total sum of all numerical values within an array of objects

Here's an example of an array:

const arr = [{
    a: 12,
    b: "A"
    c: 17
  },
  {
    a: 12,
    b: "B"
    c: 17
  },
  {
    a: 12,
    b: "C"
    c: 17
  }
];

What is the most efficient way to calculate the sum of all objects in the array? The expected result is [29,29,29]

I attempted to use

arr.map(a => Object.values(a).reduce((p,c) => p+c))
but this included non-numeric values in the result.

Answer №1

To simplify the reduction process, filter values by type before performing the operation

const arr = [{a: 12,b: "A",c: 17},{a: 12,b: "B",c: 17},{a: 12,b: "C",c: 17}];

let final = arr.map(a => Object.values(a).filter(v => typeof v === 'number').reduce((p, c) => p + c))

console.log(final)

You can also achieve the same result within the reduce method itself by adding the current value based on its type, adding 0 if the type is not number

const arr = [{a: 12,b: "A",c: 17},{a: 12,b: "B",c: 17},{a: 12,b: "C",c: 17}];

let final = arr.map(a => Object.values(a).reduce((p, c) => p + (typeof c === 'number' ? c : 0)))

console.log(final)

Answer №2

To decrease the value directly, you can use a finiteness check.

const
    array = [{ a: 12, b: "A", c: 17 }, { a: 12, b: "B", c: 17 }, { a: 12, b: "C", c: 17 }],
    result = array.map(o => Object
        .values(o)
        .reduce((s, v) => s + (isFinite(v) && v), 0)
    );

console.log(result);

Answer №3

Whether you consider the possible construction {a: "12"} as a number or a string will determine the result you receive. Using the isFinite function in this case will lead to an incorrect result.

If you view {a: "12"} as a number, you can utilize the following code:

const
    array = [{ a: "12", b: "A", c: 17 }, { a: 12, b: "B", c: 17 }, { a: 12, b: "C", c: 17 }],
    result = array.map(o => Object
        .values(o)
        .reduce((s, v) => s += +v || 0, 0)
    );

console.log(result);

If you perceive {a: "12"} as a string, you can implement the following code:

const
    array2 = [{ a: "12", b: "A", c: 17 }, { a: 12, b: "B", c: 17 }, { a: 12, b: "C", c: 17 }],
    result2 = array2.map(o => Object
        .values(o)
        .reduce((s, v) => s += (typeof v === 'number') ? v : 0, 0)
    );

console.log(result2);

Answer №4

Here's an alternative way to approach the problem:

data = [{x: 10, y: "A", z: 20},{x: 15, y: "B", z: 25},{x: 20, y: "C", z: 30}];

var output=Object.values(data).reduce((accumulator, element)=>{
   let entries=Object.entries(element), sum=0;
   entries.forEach(([key, value])=>{if(!isNaN(value))sum+=value;});
   accumulator.push(sum);
   return accumulator;
},[]);
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

Establish a default route within a Node Express application to handle multiple generic URLs (url/index, url/index2, url/index3, and

Currently, I am in the process of learning React and Express frameworks through exercises provided by NodeSchool.io. My goal is to consolidate all exercise files into a single application with multiple pages named as: index index2 index3 index4 .. ...

Animating an object in Three.js as it transitions smoothly between two different positions

If I have an object positioned at position.x = 0 and I wish to animate it smoothly to position.x = 2.435 in the render loop, how can I achieve this effect? ...

Implementing event listeners with AngularJS after making a POST request

As I delve into the world of development, please forgive my lack of knowledge. My search for solutions brought me here. I am currently working on a comment and reply app. In order to add comments to my view, I am utilizing this specific function. $scope.i ...

What are the steps to switch multiple CSS styles for creating a dark mode?

I'm currently using a combination of HTML, CSS, and JavaScript to construct my website. One feature I'd like to implement is a Darkmode switch button that toggles between Dark and Light mode when clicked. However, the issue I'm facing is tha ...

Unable to hear sound on Mozilla Firefox

I am facing an issue with playing an audio file using the audio tag inside the body element. The audio plays perfectly in Chrome once the body has finished loading, but it fails to play in Mozilla Firefox. I even attempted to download the audio file and pl ...

Minor Chrome compatibility problems with CSS alignment

As someone who is new to stackoverflow, I've always found it to be a valuable resource for answers. I've had success building HTML 5 banner ads using GSAP (Greensock Animation Platform) in the past, but now I'm facing a CSS alignment issue t ...

Obtaining the pathname in a NextJS file like _document.js is a matter of accessing

I'm looking to retrieve the current URL path in my /page/_document.js file. I've created a class and my goal is to implement a conditional statement based on this value. Below is the code snippet (similar to the example provided in NextJS docume ...

Issue found in React Js test - TypeError: source.on does not exist as a function

I'm encountering an issue with my post request using multipart/form-data. Everything runs smoothly, except for the tests which are failing. When running the tests, I encounter an error message: TypeError: source.on is not a function. This is the code ...

The sequence of Angular directives being executed

When multiple directives are applied to an element in AngularJS, what determines the order in which they will be executed? For instance: <input ng-change='foo()' data-number-formatter></input> Which directive, the number formatter ...

Issue with ngTable: Error retrieving data for server-side pagination

I am currently working on setting up a server-side table using ng-table. However, I am encountering some issues with the getData function. It keeps giving me errors such as $defer.resolve is not a function or params is not defined. I noticed that I can ac ...

Verify whether the value is considered false, true, or null

When dealing with variables in JavaScript, I often need to determine if a variable is false, true, or null. If the variable is null or undefined, I want to assign an array to it by default. While this syntax works well in other languages, in JS assigning a ...

Incorporate the ng2-ace library into a newly generated Angular-CLI (Angular2) project with the help of SystemJS

After setting up my angular2 project using the latest angular-cli tool, I decided to integrate the ace editor with the help of the ng2-ace library. My goal was to implement this in a clean manner using SystemJS as the module loader. I started by running ...

How can you eliminate a specific element from an HTML document?

Utilizing localStorage can be tricky when it comes to keeping the JSON file hidden from being displayed on the HTML page. One approach I used involves sending the JSON file to the client once and then performing all logic using that file. To prevent the JS ...

Console shows successful jQuery ajax request, but the callback function is not being executed

I've been working on a jQuery POST request that's been giving me some trouble. Here is a snippet of the code I'm using: $.ajax("/myurl",{ data:{ ... }, mimeType:"application/json", dataType:"application/json", me ...

Learn how to iterate over an array and display items with a specific class when clicked using jQuery

I have an array with values that I want to display one by one on the screen when the background div is clicked. However, I also want each element to fade out when clicked and then a new element to appear. Currently, the elements are being produced but th ...

href not functioning properly on subsequent clicks, whereas onclick remains active

I'm experiencing an issue with a button that opens a modal. When clicking the button, it's supposed to open a new page in the modal and also make an API call for processing before loading the new page. <a class="btn btn-primary" type='b ...

Mapping memory for FirefoxOS is like equivalent strides

Is there a way to create a memory mapped file in FirefoxOS, Tizen or other pure-JS mobile solutions? In the scenario of a mobile browser where you have large amounts of data that can't fit in RAM or you prefer not to load it all at once to conserve R ...

How to leverage tsconfig paths in Angular libraries?

While developing an Angular library, I made configurations in the tsconfig.lib.json file by adding the following setup for paths: "compilerOptions": { "outDir": "../../out-tsc/lib", "target": "es2015", "declaration": true, "inlineSources ...

When a model is changed from within a jQuery event, Angular 2 fails to update the view

During the development process, I encountered an issue while creating a custom search panel that displayed search results in a dropdown container. In my controller, I defined the following: export class ProductSearchComponent implements OnInit { publ ...

This function named error is implemented in native code

My website is built in C# using asp.net. When the Onchange() event is triggered on the Dropdownlist, I call this jQuery function which displays an error: function error(){[native code]} <script type="text/javascript"> function GetDescription ...