Iterate through an array to calculate the total sum of elements within subarrays associated with distinct entities

Apologies if the title was a bit unclear. Let me try to elaborate on the question: I have an array with some sample data as shown below:

const data = [
{
  name: "Bob",
  items: [1]
},
{
name: "charlie",
items: [1,2]
},
{
name: "Chris",
items: [5]
}

]

I've organized the items in arrays because there can be more than one item sometimes. Now, my question is how can I calculate the sum of all these items, which should equal 4? (the first array has 1 element, the second array has 2 elements, and the last one has 1 element) I've been struggling with this and tried using map and reduce functions, but it hasn't worked as expected... Appreciate any insights or solutions you guys might have. Thank you!

Answer №1

data.filter(element => {
  var total = element.items.reduce((sum, current) => sum + current, 0);
  if(total === 9) return element
})

Answer №2

To find the total length of all the items arrays in the data object, you can utilize the .reduce method:

const info = [
  { name: "Alice", items: [4] },
  { name: "Bob", items: [1,2,3] },
  { name: "Charlie", items: [7,8,9] }
];

const totalLength = info.reduce((count, { items = [] }) => count + items.length, 0);

console.log(totalLength);

Answer №3

Give this a shot:

let totalItems = 0;
for (let j = 0; j < jsonData.length; j++) {
  let obj = arrayOfJSONObjects[j];
  totalItems += obj.items.length;
}

Loop through the JSON objects in the array and accumulate the length of each "items" array to get the total count

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

"Creating a never-ending scroll feature for your Vue.js application: a step-by-step

Currently working on a photo gallery project using Vue and Unsplash API. I am looking to implement an infinite scroll feature for loading images. The API I have is structured like this: "https://api.unsplash.com/photos?page=1". How can I set it up so tha ...

How do I specify the return type of a function in Typescript that can return more than one type?

I am facing a situation where I have a method called getFilters that retrieves various types of values. getFilters(): IListFilteringType {...} type IListFilteringTypeMultiSelect = (string | number)[]; type IListFilteringType = boolean | string | number | ...

Tips for using jQuery to add several image source URLs to an array

My JavaScript code uses jQuery to collect all image sources on document load and store them in an array: var sliderImg = []; sliderImg.push($('.thumbnail').children('img').attr('src')); Then, I have a click event set up to a ...

Finding the Maximum Minimum Value in an Array using Pointers in C

Having a technical issue where the minimum and maximum values are not displaying correctly when I run the program. Any ideas on how to fix this? I need the range to be visible on the screen. I attempted using pointers to solve the problem. While there ma ...

Defaulting summernote to display in italics

Looking for a way to italicize a series of summernote inputs by default? I have removed all toolbar options except the italics button. Here's the HTML generating these inputs: <div style="width:250px;"> < ...

Tips for transforming promise function into rxjs Observables in Angular 10

As a beginner in typescript and angular, I am trying to understand observables. My query is related to a method that fetches the favicon of a given URL. How can I modify this method to use observables instead of promises? getFavIcon(url: string): Observ ...

How does the URL play a role in asynchronous functions when it comes to web scraping?

Currently, I am diving into web scraping and encountered a scenario that has left me puzzled regarding the arrow key function. I am struggling to comprehend why the URL is used twice and how it actually functions. Although I recognize this involves advance ...

Previewing multiple selected files in Angular interface

As a newcomer to Angular, I am currently working on a feature that involves selecting multiple files and displaying their previews before uploading them to the server. While my code works correctly when individual files are selected one at a time, it fail ...

When there is only one value, the BehaviorSubject can be hit multiple times

Recently, I implemented BehaviourSubject in a shared service to retrieve the current value when clicking a button. Everything seems to be working fine, however, there are instances where the API call within the subscribe block of BehaviourSubject is being ...

When using JavaScript's async await, a promise is being returned instead of the expected result

Can anyone help me understand why I am receiving Promise { <state>: "pending" } when I call GetProfile("username")? Any suggestions on what steps I should take? Here is the function I am referring to: const GetProfile = async ( ...

The addition of days is producing an incorrect result

When extracting the date from FullCalendar and attempting to edit it, I noticed that moment.js seems to overwrite all previously saved dates. Here is an example of what's happening: var date_start = $calendar.fullCalendar('getView').start.t ...

Upgrade the WordPress light editor to the advanced version

After developing a script to upgrade the WordPress editor on a specific page from light mode to Advanced once a user clicks the Unlock button and confirms their desire to make the switch, an issue arose. Despite deducting 5 coins from the user's balan ...

Include an array into a multidimensional matrix array using PHP

Adding an array to a multidimensional matrix array is what I want to do. For example: $a = array ('a','b','1'); $b = array ('b','c','1'); $matrix += $a; $matrix += $b; //data in $ma ...

Steps for converting a pandas dataframe into a transaction matrix

I am looking to transform my pandas dataframe into a Markov chain transaction matrix import pandas as pd dict1={'state_num_x': {0: 0, 1: 1, 2: 1,3: 1,4: 2,5: 2,6: 2,7: 3,8: 3,9: 4,10: 5,11: 5, 12: 5,13: 5,14: 5,15: 5,16: 6,17: 6 ...

Having a hard time implementing a subtracting callback function in a JavaScript reduce function

Currently, I am tackling a code challenge in JavaScript that requires me to develop a function called reduce. This function is responsible for reducing a collection to a value by applying a specific operation on each item in the collection over which it it ...

Sending text content using AJAX

Recently, I've delved into the world of AJAX and JavaScript while working on a project in JSP. My goal is to submit text entered in a textarea using a JavaScript button. The first submit button worked fine initially, but upon posting, I ended up with ...

Three.js - Illuminated Sprites

I am currently working on a 3D maze game where the walls are rendered as Meshes affected by a PointLight. However, I am encountering an issue with some objects that are implemented as Sprites - they appear fully illuminated, similar to MeshBasicMaterial. ...

Emphasizing sections using a specific class for paragraph highlighting

Is it possible to dynamically change the style of paragraphs based on certain classes? Let's say we have a text with a list of p elements and we want to modify the styles of paragraphs that come after specific classes, such as 'alert' or &ap ...

Updating the state of a Next.JS router component with React.JS: A step-by-step guide

I've implemented a toggleswitch in my app that changes its state based on the dynamic URL parameters. For instance, if the URL includes a parameter named followType set to following (e.g. https://www.example.com/home?followType=following), I want the ...

What is the best way to design a button that can toggle a sidebar on and off

I'm struggling with creating a toggle button for the sidebar. I have the sidebar and the button ready, but I'm not sure how to make the toggle function work. Can someone please guide me on what steps I need to take to achieve this? Your help woul ...