collaborating with complex structures within an object

This question may seem simple, but despite my efforts to search through Google and other resources, I can't seem to find the answer.

My array of objects looks like this:

 const myArr = [
     [{
         id: 1,
         price: 200,
     }, {
         id: 2,
         price: 900,
     }, {
         id: 3,
         price: 100,
     }],
     [{
         id: 5,
         price: 100,
     }]
 ];

In simpler terms, I have an array that contains nested arrays, each with objects inside them.

 arr [ [ {},{},{} ] ,   [ {} ]    ]

Now, my goal is to determine two things:

  1. The total count of all products
  2. The sum of prices for all products

(each object counts as one product)

Answer №1

Merge arrays into a single array using the spread syntax in JavaScript's Array.concat().

Calculate the sum by utilizing Array.reduce().

The length of the flattened array determines the count.

const myArr = [[{"id":1,"price":200},{"id":2,"price":900},{"id":3,"price":100}],[{"id":5,"price":100}]];

const flattened = [].concat(...myArr);
const count = flattened.length;
const sum = flattened.reduce((s, o) => s + o.price, 0);

console.log('count', count);
console.log('sum', sum);

Answer №2

You can utilize the spread operator to flatten the array:

var myArr = [
 [
   { 
     id:1,
     price:200,
   },

   { 
     id:2,
     price:900,
   },

   { 
     id:3,
     price:100,
   }
 ],

[
  { 
     id:5,
     price:100,
   }
]
];

var arr = [].concat(...myArr);
console.log('Length: ', arr.length);
var sum = arr.reduce((m, o) => m + o.price, 0);
console.log('Sum: ', sum);

Answer №3

A clever trick is to use the concat method to combine all objects into a single array.

To determine how many objects are in the array, simply use the length property and then utilize the reduce method to calculate the total sum.

const myArr = [ [ { id:1, price:200, }, { id:2, price:900, }, { id:3, price:100, } ], [ { id:5, price:100, } ] ];

arr = myArr.reduce((acc, arr) => acc.concat(arr), []);
sum = arr.reduce((acc, item) => acc + item.price, 0);
console.log('count ' + arr.length);
console.log('sum ' + sum)

Answer №4

Using ES6 to Sum Array Values

If you want to calculate the sum of array values in JavaScript, you can utilize the reduce method.

The reduce method allows you to iterate through an array and add each element value to the sum of previous elements.

Check out this demo:

const myArr = [[{id: 1,price: 200,}, {id: 2,price: 900,}, {id: 3,price: 100,}],[{id: 5,price: 100,}]];
  
let result = myArr.reduce((r,v)=>{
  r.count += v.length;
  r.sum += v.reduce((total,{price}) => total+price,0);
  return r;
},{count:0,sum:0}) 

console.log(result);
.as-console-wrapper {max-height: 100% !important;top: 0;}

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

What is the reason that I have to submit my mapped function twice in order for the updated state to show after modifying the array content?

When I try to display an image for the current value in the array item, the image does not display when I submit my value. I have to submit twice to display the value. Additionally, when changing the value and pressing submit, the content in the div does ...

You need to click the React onClick button twice in order to successfully trigger the API

I want to configure React so that when clicked, it will run process.env.REACT_APP_LOGOUT and remove the item set in local storage. Currently, it requires two clicks to execute. The first click redirects to the index page, and then a second click is needed ...

Can the Caption Adapt to the Image?

Code snippet: <script type="text/javascript> function displayNextImage() { x = (x === images.length - 1) ? 0 : x + 1; document.getElementById("img").src = images[x]; } function displayPreviousImage() { x = ...

Troubleshooting Challenges with JavaScript DOM Manipulation

I am facing an issue with a table where I need the first column to remain fixed when scrolling horizontally. The code snippet below works perfectly for the first column of td's, but fails to work for the tr's. Despite checking the code thoroughly ...

Convert JSON response date format to a format specified by the user

The following code snippet is currently returning the dates for $("#dob") and $("#anniversery") as 2014-04-01T00:00:00 This is my current code: <script> $(function() { function log(message) { $("<div>").text(message).p ...

How to use jQuery to set multiple variables with just one chain command?

Can you create multiple variables using a single jQuery chain? var sectionTable = jQuery("#sectionsTable"); var sectionTableRows = sectionTable.find("tr"); var sectionTableColumns = sectionTableRows.find("td"); I am curious about the syntax for chaining ...

What is the method for invoking Gruntfile tasks programmatically using code?

Is there a way to access and execute tasks from Gruntfile in my code? Appreciate any help! ...

Is it reliable to directly input $_POST data from an array into a MySQL statement for security purposes?

Recently, I coded a function that utilizes an array to post data into a MySQL table. The data is collected from the $_POST items in a form. One thought that keeps popping up in my mind is whether there are any security vulnerabilities lurking in this code. ...

How do I add a "Switch to Desktop Site" link on a mobile site that redirects to the desktop version without redirecting back to the mobile version once it loads?

After creating a custom mobile skin for a website, I faced an issue with looping back to the mobile version when trying to add a "view desktop version" link. The code snippet below detects the screen size and redirects accordingly: <script type="text/j ...

Combining multiple promises in Angular into a single promise

I have a dilemma with my services - they both return the same type of objects but with different properties based on a flag. These services utilize functions that return promises. Service 1 - fetchLocations: this.fetchLocations = function () { ...

Utilizing a CSS property within jQuery

Here is the code snippet: http://jsfiddle.net/cmac2712/dnLgD/ $(document).ready(function () { var setVisibility = function(n){ $('#content1').css('visibility', 'hidden'); $('#content2').css(&apos ...

Searching for a single cell within an HTML table

I've been on the hunt for a code that can search through a table and show just one cell. I tried creating my own, but finally stumbled upon one that seems to work perfectly, except for one hiccup. When the search bar is cleared, it displays the first ...

Why is there an alphabet or letter inside the brackets of an array? And why is this occurring inside a for loop?

How does the variable "x" function within the array's brackets and loop in the code snippet below? (This example demonstrates logic using C#) #include <iostream> #include <string> using namespace std; int main() { int myArr[5]; / ...

Determine the number of rows in an Ajax-fed datatable (including paginated rows) that have a specific value in a

I am struggling with counting rows in #datatableOne where the 'Status' column has a value of 'Unknown'. I have attempted a couple of solutions, but they are not giving me the desired results. The first solution only counts the rows on ...

The total calculations for each row in Javascript and Ajax are experiencing glitches and are not functioning correctly

Below is the script utilized by an AJAX library and JavaScript. The total order column for total price is functioning correctly. However, the total calculations for the discount column and net price column are not working as expected. <script type="te ...

How to Incorporate an Anchor Link into a Div as well as its Pseudo Element using CSS, Javascript, or jQuery

How can I make both the menu item and its icon clickable as a link? When either is clicked, the link should work. Here is a CodePen example: http://codepen.io/emilychews/pen/wJrqaR The red square serves as the container for the icon that will be used. ...

What could be causing me to receive a '+' symbol instead of a ',' when utilizing the split function in Node.js?

I have a text file (.txt) containing various pick-up lines, with each line representing a different phrase. Here's an example: Does this rag smell like chloroform to you? I have amnesia - do I come here often? Your lips look lonely. Let me introduc ...

Why are cloned jQuery elements triggering events on the parent <div> and not the child <div>?

Currently, I am working on a tool that includes dynamic input fields for user input. To create different sections, I have cloned some divs from the code successfully. However, I am facing an issue where the events attached to the parent div are triggered e ...

"Utilizing the Nuxt Vue Router afterEach Guard for Added Security

Is there a way to implement an afterEach handler in Nuxt that runs after route changes? While middleware can be used as a beforeEach, I'm struggling to find a solution for the afterEach hook. ...

What is the best method to collect information from multiple AJAX requests?

In addition to synchronous AJAX calls, what is the most effective approach for handling a situation like this? var A = getDataFromServerWithAJAXCall(whatever); var B = getDataFromServerWithAJAXCallThatDependsOnPreviousData(A); var C = getMoreDataFromServe ...