Colin747
Colin747

Reputation: 5013

JavaScript data arrays doubling in value

I'm looking to return data from a REST end point to populate a graph on a button press. If the button is pressed twice then the data is doubled, however, in this case I would like the old data to be deleted and only the new data to be displayed.

E.g. On first button press this is the data returned:

{19455746: 28, 22254286: 83, 22255638: 136, 22808354: 34}

On the second button press this is returned:

{19455746: 56, 22254286: 166, 22255638: 272, 22808354: 68}

In this case I would just want the following returned on the second button press:

{19455746: 28, 22254286: 83, 22255638: 136, 22808354: 34}

My JavaScript code that the button press triggers is below, I've tried to cut this down to what I believe to be relevant, let me know if more code is required):

$scope.getDateRangeRoom = function () {
    $scope.data = null; 
    var obj = {};
    condata = null;
    ...
    $q.all(NexaService.getRoomDateRange(roomName, startDate, secondDate))
            .then(function (response) {
                for (var x = 0; x < response.length; x++) {
                    conData.push(response[x].data);
                }
                $scope.loaded = true;
                for (var x = 0; x < conData.length; x++) {
                    for (var i = 0, j = conData[x].length; i < j; i++) {
                        if (obj[conData[x][i].sensorUUID]) {
                            obj[conData[x][i].sensorUUID]++;
                        } else {
                            obj[conData[x][i].sensorUUID] = 1;
                        }
                    }
                }
                var sensorNameArray = Object.keys(obj);
                var sensorDataArray = sensorNameArray.map(key => obj[key]);
                $scope.data = sensorDataArray;
                ...
}

How can I make sure that the previous data is deleted and only the new data returned?

Upvotes: 0

Views: 62

Answers (1)

raina77ow
raina77ow

Reputation: 106385

Replace condata = null; with var conData = [] line. You only need this variable within the function AND it has to be another - empty - array each time you call getDateRangeRoom().

You didn't show where this variable is created currently; my understanding is that it's a shared state of scope. Even if you turn it into an empty array, there's a chance it'll be repopulated twice (or even more) on .then calls.

... and if, by some reason, you indeed this to be shared, clean it only exactly before the repopulation. For example:

.then(function (response) {
  conData = [];
  for (var x = 0; x < response.length; x++) {
    conData.push(response[x].data);
  }
  // ... there goes the rest

In fact, you can write this even more concise:

conData = response.map(row => row.data);

Upvotes: 2

Related Questions