How to include a for loop within an array as an element

Below is an illustration of the data available:

$scope.allmovies[
{title:"Harry Potter", time:130},
{title:"Star Wars", time:155},
{title:"Lord of the Rings", time:250},
{title:"Goonies", time:125},
{title:"Fast and Furious", time:140}
];

var mostpopular=[
$scope.allmovies[0],
$scope.allmovies[2]
];

var recentlyadded=[
$scope.allmovies[1],
$scope.allmovies[3],
$scope.allmovies[4]
];

$scope.playlists={

mostpoplularmoves:{
title:"Most Popular Movies",
price:"$5.99",
Number:mostpopular.length,
TotalTime: LOOP THROUGH VAR MOSTPOPULAR AND CALCULATE THE TOTAL TIME OF ALL MOVIES
},

recentlyaddedmovies:{
title:"Recently Added Movies",
price:"$2.99",
Number:recentlyadded.length,
TotalTime:LOOP THROUGH VAR RECENTLYADDED AND DETERMINE THE TOTAL TIME OF ALL MOVIES
}

};

I need help in looping through the arrays above to sum up all the times and obtain a total time for each playlist (mostpopular[0].time+=totalTime then mostpopular[1].time+=totalTime etc.... or something similar). Is this achievable and if so, what would be the correct syntax? Thank you for your assistance

Answer №1

To achieve this, consider employing a reduce method

mostpopular.reduce(function(totalTime, movie) {
  return totalTime + movie.time;
}, 0);

The reduce functions involve an accumulator (totalTime) and the current value in the array as the second argument. The 0 at the end indicates the initial totalTime value. After modifying totalTime in the reduce return statement, it becomes the totalTime argument for the next array element.

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

Setting state back to default following the conditional rendering of a React component

Whenever the save button is clicked, I aim to display a snackbar component by updating the showSnackbar state to true. To achieve this in React, it's just a simple conditional check in the main render method. The snackbar I'm using here automatic ...

How can I update the style of my array-bars using componentDidMount()?

I created a visualization tool for sorting algorithms that displays vertical bars with varying heights and sorts them. The "Generate new Array" button triggers a function to generate a new array each time it's clicked, which is also used in the compon ...

Using TypeScript with React and Redux to create actions that return promises

Within my React application, I prefer to abstract the Redux implementation from the View logic by encapsulating it in its own package, which I refer to as the SDK package. From this SDK package, I export a set of React Hooks so that any client can easily u ...

What is the best way to incorporate template literals (` `) into existing template literals?

I am facing a unique challenge where I need to utilize a template literal within another template literal, but I am struggling to make it work. The code snippet in question looks like this: <p>Something something <a href={`${SOMELINK}/blah`}> ...

Turn off link preview feature on Android messages

As a developer, I am looking for a way to disable or hide link previews on Android devices when someone receives a text message with a link to our website. I still want the URL address to be visible, but I prefer to keep the link previews on IOS devices. I ...

Updating the text of a Mat-Label dynamically without the need to reload the page

In my application, there is a mat-label that shows the Customer End Date. The end date is fetched initially through a GET request to an API. Let's say the end date is 16-05-2099, which is displayed as it is. There is also a delete button implemented f ...

Exploring the intricacies of React Router parameters

I have been facing some issues with my routing setup. Specifically, I have a static route called list and a dynamic route called user/:id. The problem arises when navigating between these two pages. (1) Whenever I navigate to the list route from the user/: ...

Positional vs Named Parameters in TypeScript Constructor

Currently, I have a class that requires 7+ positional parameters. class User { constructor (param1, param2, param3, …etc) { // … } } I am looking to switch to named parameters using an options object. type UserOptions = { param1: string // ...

Issue with conflicting versions in Bower dependencies

Just starting out on an angular project and incorporating bower. I've added two packages with --save to update my bower.json file. After running bower update, this is the result I get: Please take note that, ng-token-auth#0.0.29 requires an ...

Getting data before the Router is loaded following authentication with Angular 2+ - A comprehensive guide

I'm hoping this isn't a repeat. Within my login component, I have a feature that allows users to log in, which calls a service and retrieves a Token. Upon successful login, the token is saved to localStorage. Subsequently, I use the getUserData ...

What causes images to expand automatically when selected in my JavaScript gallery?

I am struggling with a simple JS gallery of images where I want to display a large image at the top and small thumbnails below it. The issue I am facing is that when I hover over an image in the thumbnail section, the big image changes as expected. However ...

What are the steps to set up mocha to automatically monitor source or project files?

Is there a way for Mocha to only watch my source/project files and not the test files? The test files and source/project files are located in separate directories. Any help or guidance would be greatly appreciated. Thank you! ...

What is the reason behind the C# button_clicked function not triggering the Javascript function?

When the user clicks the button, I want to test the C# code side. The method in the C# function should call a JavaScript function to display an alert with the results of a C# public variable. However, it seems that nothing is being called at all. At the bo ...

Loading an Angular app causes Chrome devtools to freeze

Currently, I am facing some unusual behavior in my rather large Angular (1.5) application. When I have Chrome DevTools open while loading the app, the CPU usage of that particular tab shoots up to 100%, causing the app to take a minute or more to load. Add ...

Check the feature that retrieves data from a `json` file

In my util file, I have a function that imports and checks whether a given sectionUUID has a video in the JSON file. import multipleVideos from '../data/videos.json' function hasSectionMultipleVideos (sectionUUID) { return multipleVideos.vide ...

The compatibility of ng-switch-when and ng-class

Is it possible to use ng-switch-when and ng-class together on the same element without any compatibility issues? I am facing some trouble dynamically changing the class of multiple elements simultaneously. It seems to only work on the currently displayed e ...

What could be causing the lack of data for the current user?

I have been attempting to fetch the current user session and display the data in the view, but nothing is appearing. I even checked the database and confirmed an active session with all the necessary information. I attempted logging the user out and starti ...

In ReactJS, when you encounter TextField values that are "undefined", it is important to handle them appropriately

I'm a beginner when it comes to ReactJs and Material-UI, so please bear with me if my question seems silly. Currently, I have a file named Main.js which includes the following code snippet: handleChange = (name, event) => { if(event==null) ...

Hide the previous dropdown content in Vue JS by manipulating the visibility of the elements

I'm currently working on creating a Dropdown feature, but I'm facing an issue with hiding the dropdown content when another dropdown is clicked. <template> <div class="dropdown-container"> <div v-for="(it ...

tips for selecting various API requests based on the selected drop down menu choice

Hey there! I'm looking to enhance my login page by adding a feature that allows users to select from a dropdown menu with different options. Each option will be linked to a specific API, and based on the API response, the user's ability to log in ...