Retrieving a property of an object within an array using JavaScript in AngularJS

Seeking advice on how to calculate the total price of products in an array when working within a callback function. Is there a method similar to myArray.(intheobject).price? Or is there a way to handle callbacks effectively to achieve accurate results?

this.productList = [
    {
      type: 'chocolate',
      pack: '3',
      price: 5,
      checkState: false
    },
    {
      type: 'chocolate',
      pack: '5',
      price: 7,
      checkState: false
    },
    ...
 ]

.filter('calculateTotal', function(){
  var totalCost = 0;
  return function(input){
    return totalCost + ???
  }    
})

Thanks to PierreDuc's suggestion, my updated filter looks like this:

.filter('calculateTotal', function(){
  return function(input){
    return input.reduce((total, item) => item.price + total, 0);
  }    
})

Answer №1

If you're looking to calculate the total price using JavaScript, the reduce method is a great option:

const totalPrice = [{
    type: 'chocolate',
    pack: '3',
    price: 5,
    checkState: false
  },
  {
    type: 'chocolate',
    pack: '5',
    price: 7,
    checkState: false
}].reduce((total, item) => item.price + total, 0);

The filter method can help narrow down your array based on specific criteria.

By utilizing the reduce function, you can modify your array by starting with an initial value of 0. This initial value will be assigned to the total parameter within the callback function, while item represents each element in the array. The output of the callback function determines the new value for the total parameter.

Answer №2

When using the filter callback, each element can be accessed individually. To store the sum of all values, create a global variable outside the callback function and update it within the function. Detailed information can be found in the filter documentation.

this.totalCost = 0;

this.productList = [
    {
      type: 'chocolate',
      pack: '3',
      price: 5,
      checkState: false
    },
    {
      type: 'chocolate',
      pack: '5',
      price: 7,
      checkState: false
    },
    ...
  ]
var self = this;
angular.module('myReverseFilterApp', [])
.filter('calculateTotal', function(){
      return function(input) {
           self.totalCost += input.price;
      }
})

The total sum stored in the totalCost variable can then be accessed in your HTML code. It is not possible to directly return the total sum from the filter function since it operates on each element individually within the array. Therefore, correct syntax implementation is crucial for functionality.

Answer №3

const shoppingList = [
    {
      item: 'apple',
      quantity: '3',
      price: 2,
      inCart: false
    },
    {
      item: 'banana',
      quantity: '5',
      price: 4,
      inCart: false
    },
    {
      item: 'orange',
      quantity: '10',
      price: 3,
      inCart: false
    }
  ]
let totalCost = shoppingList.reduce(function(sum, currentItem, index, array) {
  return sum + currentItem['price']
}, 0);
console.log(totalCost)

Answer №4

To achieve this, start by gathering all the prices into an array and then use the reduce function to carry out operations on the prices. Make sure to refer to the documentation for more details on how to use the reduce function:

reduce documentation

let priceList = [];
itemList.forEach(item => {
    priceList.push(item['price']);
})

let totalPrice = priceList.reduce((currentPrice, nextPrice) => currentPrice + nextPrice, 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

Update the CAPTCHA, while also refreshing the entire registration form

JavaScript Snippet <script language="javascript" type="text/javascript"> function updateCaptcha() { $("#captchaimage").attr('src','new_captcha_image.php'); } </script> New Image Code <img src="new_ ...

Interaction between the Vue parent and any child component

I am working with a series of components that are structured in multiple levels. Each component has its own data that is fetched over AJAX and used to render child components. For instance, the days parent template looks like this: <template> &l ...

Having trouble getting your jQuery code to work in your HTML document after converting it to

Recently, I've been working with HTML5, CSS, and vanilla JavaScript. I wanted to convert this jQuery code and make some changes to it. However, I seem to be encountering an issue after implementing the new code. The original code had a small triangu ...

What is the best way to condense a repetitive method declaration and make it more concise?

I'm facing a situation where I have declared similar const values. Here's my current setup... import React from 'react' function Component_a() { const x = 5; const y = 10; const image_a = [...Array(x)].map((e, i) => ...

Any ideas on how to fix the error that pops up during the installation of the bootstrap package in Node

The npm command is not recognized as a valid cmdlet, function, script file, or operable program. Please double check the spelling of the command and ensure that the path is correct before trying again. This error occurred at line 1. npm i bootstrap + ...

Receiving a 404 error when attempting to use the 'import' statement within a script tag labeled as a module

I am currently working on a NodeJS project that utilizes Webpack for bundling and Express for serving. Whenever a user visits the root domain, they are served an index.html file containing a <script> block in the footer with a type of module. index. ...

It is necessary to render React Native text strings within a text component

Greetings! The React Native code snippet below is responsible for rendering a user interface. However, upon running the code, an error occurred. How can I resolve this issue? The error message indicates that text strings must be rendered within a text comp ...

Click the submit button to display a div element without having to refresh the page

Is it possible to display a spinner for a couple of seconds before the page reloads upon submitting a form? <form class="ready" action="https://link.com" method="post"> <input name="test" type="submit" class="click" value="order"/> </form&g ...

Implement AJAX and PHP to submit form data along with the page ID and session information

I am currently developing a school book library website project that allows students to browse and select books, as well as send requests to the librarian to borrow them. However, I am still learning jQuery and facing some challenges in handling issues. H ...

Utilizing AngularJS for manipulating a multidimensional array with interdependent select boxes

I have a unique collection of product names along with their respective versions stored in a multidimensional array. My goal is to design an interactive interface that allows users to first select a product from a drop-down menu and then choose the version ...

Function triggered twice upon checkbox being selected

Below is the code snippet I am using: $("#cc1").unbind('click').click(function(e) { //somefunction }); This code works perfectly fine for executing a function after clicking the cc1 button. However, when I use the following code: $("#cc1" ...

What is the best way to incorporate child nodes when selecting dynamically generated elements through JavaScript?

Currently, I have buttons being dynamically generated on the page using plain JavaScript. For example: <button class="c-config__option c-config__option--button c-config__option--pack" data-index="0"> Item 1 <span>Subtext</span> ...

Display a recurring list within an Ionic Pop Up

I am facing an issue with a collection repeat list that includes a search bar at the top of the list. When displayed on a real Android 4.4 device, only 9 records are showing up. I have created a codepen example here, where all the records are displayed co ...

Linking Angular with property of an object

Is there a way to ensure that the binding of object properties works properly? For instance, in my controller I have: $scope.reviews = { rating_summary: 4, items: [ { title: 'A Title'}, etc... ] } And in my view: <li ng-repeat="review i ...

Adding elements to a roster

Can anyone assist me with appending data from a csv file to an unordered HTML list? The csv file I have contains both single and grouped data for the list, as seen below: Test Group Name A,Test Link Name 1,Test URL 1 Test Group Name A,Test Link Name 2,Tes ...

What is the process for incorporating Material-UI into a JSFiddle project?

I'm having trouble figuring out how to load and use the Material UI script on platforms like JSFiddle or SO's code editor, even though I can add it with NPM. Check out this JSFiddle example <script src="https://unpkg.com/@material-ui/core/um ...

Can React-Select be utilized in the browser directly from the CDN?

Is it possible to utilize react-select directly in the browser without using bundlers nowadays? The most recent version that I could find which supports this is 2.1.2: How to import from React-Select CDN with React and Babel? In the past, they provided r ...

Pass data from a JavaScript function to Objective-C in Xcode by returning an array

How can I retrieve an array of strings from Javascript in my iPhone app code? I am calling a Javascript function, and once it completes, I need to send the array of strings back to the Objective-C code. What is the best way to return the array and how can ...

What occurs when multiple HTML tags are assigned the same string as their ID attribute value?

While browsing a html page, I stumbled upon several tags that I thought had the same id. It turns out they were unique, but it got me thinking - what would happen if multiple tags actually shared the same id? I've always heard that the id attribute o ...

"Sending a POST request from the smartphone application client developed using the Meteor

I'm currently working on a simple mobile app with Meteor that aims to send user location data to a geospatial database or server. However, I'm facing some challenges and uncertainties about the feasibility of this task using Meteor. The issue ari ...