When using the JavaScript .push method, existing array values are overwritten as the new values are duplicated

(using Angular) I am working on creating an array of arrays to be represented in a chart. The data values are being generated through the following code snippet:

$scope.getData = function() {
  $scope.series.length = 0
  $scope.allData.length = 0
  var dataArray = [];
  var dateArray = ["2015-04-03 00:00:00", "2015-04-04 00:00:00", "2015-04-05 00:00:00", "2015-04-06 00:00:00", "2015-04-07 00:00:00"]

  for (var i = 0 ; i < $scope.dataDisplayModel.length ; i++) {
    if ($scope.dataDisplayModel[i].checked === true) {
      var field = $scope.dataList.fields.indexOf($scope.dataDisplayModel[i].field)
      dataArray.length = 0;

      for (var j = 0 ; j < 5 ; j++) {
        var arrayList = $filter('filter')($scope.dataList.values, dateArray[j], true);
        var sum = _.sum(arrayList, field);
        dataArray.push(sum);
      }
      $scope.allData.push(dataArray);
    }
  }
}

Using the variables:

$scope.allData = the desired output array
dataDisplayModel = an array of objects containing field names and a checked property
$scope.dataList = JSON array containing the original data

However, whenever I push to $scope.allData, it seems to replace the previous arrays with duplicates. So, when checking 2 fields, the result is

$scope.allData = [[ARRAY2],[ARRAY2]]

and with 3 fields selected, it shows

$scope.allData = [[ARRAY3],[ARRAY3],[ARRAY3]]

This behavior of overwriting existing arrays is causing confusion. Any insights on why this might be happening would be greatly appreciated.

Answer №1

To ensure that you are working with a fresh array each time, it is important to create a new local array before pushing it into the main one:

    $scope.fetchData = function() {
      $scope.items.length = 0;
      $scope.allItems.length = 0;

      var dateArray = ["2015-04-03 00:00:00", "2015-04-04 00:00:00", "2015-04-05 00:00:00", "2015-04-06 00:00:00", "2015-04-07 00:00:00"];

      for (var i = 0; i < $scope.dataDisplayModel.length; i++) {
        var dataValues = []; // create a new local array in each iteration
        if ($scope.dataDisplayModel[i].checked === true) {
          var index = $scope.dataList.fields.indexOf($scope.dataDisplayModel[i].field);

          for (var j = 0; j < 5; j++) {
            var filteredList = $filter('filter')($scope.dataList.values, dateArray[j], true);
            var totalSum = _.sum(filteredList, index);
            dataValues.push(totalSum);
          }
          $scope.allItems.push(dataValues);
        }
      }
    }

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

Prevent the Scrolling on a Dynamic Web Page Using Selenium in Python

Hey there! I'm currently working on using Selenium and Scrapy to scrape some data from I've been experimenting with different methods, such as using Selenium and configuring PhantomJs as the driver. To scroll down the page, which is an infinite ...

Ways to adjust the size of div and its elements to fit the window dimensions

When resizing the window, the banner image shrinks while the header and header items remain the same size. However, there is an issue when the header takes up around 30% of the screen in phone view. Here is the CSS code I am using: .headerdiv{ width: ...

Reveal concealed roster using JavaScript

I am looking for a way to toggle the visibility of items in a list when an input is clicked. The challenge I'm facing is that the page should load with the list hidden, but the code only functions correctly if the list starts out visible. function ...

Strange behavior in Angular 4 routing: Child module not rendering unless the page is manually refreshed

I've been trying to find a solution for this strange behavior but haven't had any success. There are no errors showing in either the Angular 4 console or the JavaScript console. Currently using Angular CLI (Angular 4). I'm encountering ...

Using GraphicsMagick in combination with Node.js to upload a fresh image file to AWS S3: A step-by-step guide

I've encountered an issue while trying to upload images to S3 - phone images appear rotated due to EXIF data. To address this problem, I came across a tool called graphicsmagick which claims to remove EXIF data and resize images to 500px wide. However ...

Obtaining Position Coordinates of an Element Linked to an Object in AngularJS $scope

Imagine a website with a left column containing filters like checkboxes and text fields. The main column displays items that are filtered based on the values provided in the left column. When a user changes a value in the filter column, a small floating el ...

Is it possible to utilize a utility function to modify the state of useState during the

I have a small function for handling uploads that looks like this: const handleUploadPhoto = filename => { setHasImage('has-image'); setPostButtonState(''); onAddedPhoto(filename); setPostImageFilename(filename); }; I find m ...

obtaining the controller output in JavaScript

Scenario: Retrieving id in javascript following an ajax post I'm trying to figure out how to access the id sent from my controller's ActionResult in javascript. I've experimented with both Content Result and JSON Result on the controller, b ...

The synchronization of sessions between Socket.IO and Express is proving to be a challenge as

I am currently facing an issue with connecting the sessions of my express API and socket.IO server. It appears that both are storing their sessions independently. The socket.IO server has the connections session, while the express server has the user qid s ...

The results returned by AngularJS $q.all() come back as empty

Currently, I am working on implementing a $q.all function to execute multiple functions and then collect all the outputs in a function connected to the .then method at the end. Even though it seems like the promises are being called in the correct sequenc ...

Slow rendering occurs with unthrottled range input, even with proper throttling applied

I'm currently seeking some general guidelines because I'm unsure where to turn for help at the moment. The issue I am facing involves an uncontrolled input[type=range] slider that performs very slowly when there are numerous steps (works fine wi ...

Experiencing problems with various React Carousel libraries when it comes to displaying

I have been attempting to integrate Carousel libraries into my react app, but I am encountering a common issue with all of them. The Carousels show the items on the first slide, but subsequent slides do not display any items, even though they exist within ...

Raspberry Pi Fast Server: Issue with AJAX not locating images in directory and malfunctioning ID search

I'm completely new to Raspberry Pi, linux, and server concepts, so I'd appreciate explanations at a beginner level. My goal is to create a display similar to those you see in lobbies showing corporate slides and weather updates. While setting up ...

Creating a heading transition that moves from the bottom to the top with CSS

I am looking to add an animation effect to the H1 element in my program. I want it to smoothly appear from the bottom hidden position using a CSS transition when the page loads. How can I achieve this? Additionally, I need the height of the bounding elemen ...

What is preventing V8 from optimizing try-catch-finally blocks?

What is the reason behind V8's inability to optimize try-catch-finally blocks, while other well-known runtimes like SpiderMonkey and Chakra handle it with no issues? ...

Issues with validating the input in the form

Having trouble getting the unique user name check to work while using the jQuery valid8 plugin to validate a register form. Here is the code for Register.php <?php include ("db.php"); ?> <script src='js/jquery-1.4.2.min.js' type=' ...

Displaying a loading spinner while waiting for the Vue.js app to render

Currently, I am developing a Vue.js application and I'm facing a challenge in adding a loading spinner before the app component is rendered. Instagram has a similar feature where they display their logo before showing the page contents. I have tried v ...

The purpose of eventOverlap is to enable the inclusion of another event with a distinct tag within the same day

Here is the code snippet: eventOverlap: function(stillEvent, movingEvent) { console.log("I am overlapping something"); if (stillEvent.tags == ""|| movingEvent.tags == "") { console.log("One of the events h ...

Having trouble accessing the main screen following successful login

Please see the attached log I am facing an issue while trying to navigate to the HomeScreen after logging in. When I input a wrong user ID, I receive an alert with a message indicating incorrect credentials. However, when I input the correct information, I ...

What is the best way to extract parameters from an HTTP request while performing unit tests in AngularJS?

I have created a method in my controller that looks like this: $scope.submitForm = ( username, password ) =>{ $http({ method: 'post', url: 'balabala', params: {username, password} }).success( res =&g ...