Calculate the total value of properties within an observable array

I have an observable array that contains BookStore objects, each with a property called numberOfBooks. I want to calculate the sum of all numberOfBooks values in the array. The array is defined as:

public bookStores$: Observable;

Instead of using a simple for loop to iterate through the array, I encountered a syntax error when trying to access the count property of my array:

Operator '<' cannot be applied to types 'number' and '<T>(this: Observable<T>, predicate?: (value: T, index: number, source: Observable<T>)=>boolean)...

This error occurred while attempting:

for (let i = 0; i < this.bookStores$.count; i++){ }

What would be the correct method to calculate the total sum of numberOfBooks from each BookStore object within the array?

Answer №1

Understanding Observable.count and how to avoid unexpected results
To accurately determine the length of an array from Observable results, consider implementing the following approach:

BookStoreService.ts

...
getBookStore() : Observable<Bookstore> {
   this.bookstore$ = this.http.get(...)
      .map( (response:Response) =>  response.json() )
      .map( response => response.bookstore);  // Check if the JSON payload you require is wrapped in another container
   return this.bookstore$;
}

Component.ts

  ...
  bookstore$ : Observable<Bookstore>;
  bookstores: Bookstore[];
  numberOfBookStores:number;
  constructor(private bookService:BookService) {}

   ..
  this.bookService.getJobs()
   .subscribe(
     bookstores => {this.bookstores = bookstores;
                    this.numberOfBookstores = this.bookstores.length;
                   },
     err       => { this.bookstores = [] as BookStore[];
                    // Handle errors such as 404 more extensively in final code for better user feedback
                  },
     ()        => {
                  }
   );

Update:
If your goal is only to iterate through the list in your HTML template, declaring the bookstores array property may not be necessary. This was demonstrated to show how to calculate the size of the returned collection of bookstores.

You can utilize syntax like this:

<tr *ngFor="let bookstore of (bookstore$ |async) as bookstores; 
            trackBy bookstore?.id; let i = index">
  <td>{{bookstore.numberofBooks}}
<tr/>

Learn more about:

  • *ngFor trackBy, even, odd, first, last attributes here.
  • Using Async pipe for handling entire block of HTML template with AS here

Additionally, explore libraries like Lodash and Underscore for computing the total count of books. Although I have not personally used Underscore. Check out this basic example to begin.

If you are feeling adventurous, delve into this Functional Programming in Javascript Tutorial

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

Sorting an array of subdocuments within a populated query result in Node.js with Mongoose

I am looking to fetch recently submitted articles by members based on time. In the Member Schema, there is an array of _id values for submitted articles. Below are the details of the Member and Article Schemas: Member Schema const mongoose = require( ...

The translator tool relying on string matching is malfunctioning

A unique program was created to analyze the top 100 most frequently used words in the English language by reading from the file english_dictionary.txt. The translations of these words in a foreign language were then stored in the file foreign_dictionary.tx ...

Smoothness issue with fading in Ajax-loaded div using jQuery

When I run the code locally, the fade-in effect is very smooth. However, when it's deployed on a remote server, the content loaded into the target div initially appears, then disappears instantly before fading back in again. What could be causing thi ...

What is the best method for showing jQuery/Javascript functions in the HTML <pre> element as a string

I am curious about converting jQuery or JavaScript functions to a string and displaying them in an element like <pre> HTML : <pre></pre> jQuery : function test() { alert('test'); } $('pre').html(test()); // &l ...

Issue with retrieving POST body from Ajax call in Play Framework

I am currently attempting to send a POST request to my backend using JSON data. The frontend call appears like this: function register() { var user = $("#form_reg_username").val(); var pass = $("#form_reg_password").val(); var referal = $("#form_reg ...

Creating a dynamic list filter using JavaScript and three select boxes

Looking for a way to implement a similar feature to the one on this webpage: I will be showcasing a list of brands on the page, with each brand requiring three pieces of information: Starting letter Store (multiple options) Category (multiple options) ...

Difficulty encountered in assigning a value to a variable when utilizing an async function in Node.js

While attempting to retrieve the jwtauthtoken from the user and passing it to a function called getUserId() in the imported JavaScript file, I encountered an issue where the returned value was undefined instead of the decoded ID. The getUserId() function ...

A custom script for Google Sheets that accesses data from cell "A" and populates cell "B" with information based on the value in cell "A"

Hey everyone, I'm looking to create a script for Google Sheets that will check if there is a value in a cell within a row, and then populate another cell in the same row with a specific value. For instance, if a cell in row 2, column G contains anyth ...

Save Button Customization in TopToolbar within Edit Module

I've been struggling to create a customized save button within the TopToolbar component. Despite trying various approaches, including using the useSaveContext() method explicitly on a Button element, I can't seem to get it to work. Can anyone gui ...

Learn the process of developing a web client application using Node.js and NPM similar to the AngularJS tutorial

I am new to nodejs, npm and angularjs. I recently explored the angularjs tutorial project available at https://github.com/angular/angular-phonecat.git. This project has been really interesting for me as it demonstrates how easy it is to manage modules wi ...

Deactivate the Windows button and prevent the use of Alt + E to type in

I am looking to develop a web application called "QUIZ". In this application, I want users to be able to navigate using only the mouse as I have disabled all keys except for the windows, alt, 'num lock', and caps button. I tried to disable the wi ...

Switching PHP include on an HTML page using JavaScript

I've been attempting to modify the content of the div with the ID "panel_alumno" using a JavaScript function that triggers when a button is clicked. My goal is to display a different table each time the button is pressed, but so far, I haven't be ...

Using the output of wget to CouchDB as an array in a for-loop

When I run the wget command, I want to create an array from the output to use in a for loop: RESULT="`wget -qO- http://myCouchDBServer.com:5984/_all_dbs`" echo $RESULT The result typically looks like this: ["_replicator","_users","mydb1","mydb2","mydb3" ...

Utilizing the components within the range set by paper.setStart() and paper.setFinish() in Raphaels

My question has two parts - the first and second part. Let's consider an example code that I am working on. I am creating a map of my country with regions, and I want to perform actions on the entire map such as scaling or translating (as seen in the ...

Unable to retrieve or print the final character of a character array in C++ due to limitation

As a novice in C++, I am encountering an issue when attempting to store individual characters (including spaces) of a sentence in a char array, such as "Do or die". Strangely, whenever I print the array (char arr), it does not display the last character &a ...

utilizing the value within the useState function, however, when attempting to utilize it within this.state, the tab switching feature fails

I am struggling to implement tab functionality in a class component. Even though I'm using this.state instead of useState, the tab switching is not working correctly. I have read the following articles but still can't figure it out: http ...

Vanilla JavaScript error: Unable to access property

I am working on implementing a header with a logo and navigation that includes a menu toggle link for smaller viewports. My goal is to achieve this using Vanilla JS instead of jQuery. However, when I click on the menu toggle link, I encounter the followin ...

Each time the page is refreshed, the most recent form data submitted is continually appended to an array

I have implemented a post request to add input data from a form. The entered data is stored in an array variable burg and then displayed on my index.handlebars view. Everything works as intended, but when the page is refreshed without any input in the form ...

Error encountered during AJAX POST request: NETWORK_ERR code XMLHttpRequest Exception 101 was raised while using an Android device

Here is the ajax post code that I am using: $.ajax({ type: "POST", url: "http://sampleurl", data: { 'email':$('#email').val(), 'password':$('#password').val(), }, cache: false, ...

Looking for a way to have a form vanish from every page on your website once it's been

The form on all pages should vanish after the first submission. I am searching for a new code version that leverages a fundamental feature of web browsers $.ajax({ url: 'subscribe.php', type: 'post', data: { email ...