Error encountered when attempting to utilize the push() method on a two-dimensional

My goal is to arrange database data by their groupID (each with a different groupID in a separate sub-array). However, when I attempt to push the data into an array, I encounter the following error:

TypeError: Cannot read property 'push' of undefined
at app.js:30
at angular.min.js:136
at m.$digest (angular.min.js:147)
at m.$apply (angular.min.js:151)
at l (angular.min.js:103)
at s (angular.min.js:108)
at XMLHttpRequest.y.onload (angular.min.js:109) "Possibly unhandled rejection: {}"

The code I am using is:

$scope.tasks = [[]];
var temp = [];
var k = 0;
$scope.tempTasks = response.data;
for (var i = 0; $scope.tempTasks[i]; i++) {
    if (k > 0) {
        $scope.tasks.push( [] );
    }
    $scope.tasks[k].push($scope.tempTasks[k]);

    for (var j = 0; j < $scope.tempTasks.length; j++){              
        if($scope.tempTasks[i].groupID == $scope.tempTasks[j].groupID){
            $scope.tasks[i].push($scope.tempTasks[j]);
        } else {
            temp[k] = j;
            k++;
            continue;
        }
    }
}

This is how the response appears:

data: Array(7)
   0: {ID: 2, Title: "Don't do it", Description: "Just don't do it!", Date: "2018-01-10", groupID: 1}
   1: {ID: 3, Title: "Do it", Description: "Just do it", Date: "1999-12-31", groupID: 3}
   2: {ID: 4, Title: "asd", Description: "asd", Date: "2000-10-10", groupID: 2}
   3: {ID: 6, Title: "jnjkhjkkjh", Description: "jihjuiuiu", Date: "78-9809-99", groupID: 3}
   4: {ID: 7, Title: "asdasd", Description: "asdasdasd", Date: "2000-10-10", groupID: 4}
   5: {ID: 12, Title: "asd", Description: "asd", Date: "2000-10-10", groupID: 4}
   6: {ID: 13, Title: "asd", Description: "asd", Date: "2000-10-10", groupID: 2}

Answer №1

If you need to group data in Javascript, you can use the reduce function.

Below is an example of how you can implement it in your code:

const data = response.data;
const groupedData = data.reduce((previous, next) => {
  if(previous[next.groupID]) { previous[next.groupID].push(next); }
  else { previous[next.groupID] = [next]; }
  return previous;
}, {});

Feel free to test it out and see how it functions! If you have any questions, don't hesitate to ask.

UPDATE: Check out this working snippet:

const data = [{ ID: 2, Title: "Don't do it", Description: "Just don't do it!", Date: "2018-01-10", groupID: 1 },
  { ID: 3, Title: "Do it", Description: "Just do it", Date: "1999-12-31", groupID: 3 },
  { ID: 4, Title: "asd", Description: "asd", Date: "2000-10-10", groupID: 2 },
  { ID: 6, Title: "jnjkhjkkjh", Description: "jihjuiuiu", Date: "78-9809-99", groupID: 3 },
  { ID: 7, Title: "asdasd", Description: "asdasdasd", Date: "2000-10-10", groupID: 4 },
  { ID: 12, Title: "asd", Description: "asd", Date: "2000-10-10", groupID: 4 },
  { ID: 13, Title: "asd", Description: "asd", Date: "2000-10-10", groupID: 2 }
];

const groupedData = data.reduce((previous, next) => {
  if (previous[next.groupID]) { previous[next.groupID].push(next); } 
  else { previous[next.groupID] = [next]; }
  return previous;
}, {});

console.log(groupedData);

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

Creating a collapsible accordion feature with jQuery using a specific HTML layout: wanna learn how?

I am looking to create an accordion effect with the structure provided below. The goal is to have the corresponding article toggle when clicking on .booklist>li>a, allowing only one article to be open at a time. Can someone assist me with writing thi ...

The JavaScript function will only run after the user clicks the button twice

I attempted to create a button that toggles the visibility of a div element. Initially, I added the "onclick" event to the button and wrote this function: function showElement() { var element = document.querySelector('.blocks-fnd-div'); if ...

The addEventListener function seems to be malfunctioning in the React JS component

Initially, the program runs correctly. However, after pressing the sum or minus button, the function fails to execute. componentDidMount() { if(CONST.INTRO) { this.showIntro(); // display popup with next and previous buttons let plus = docume ...

What is the fastest method for slicing a Python list using a NumPy array of indices?

I am dealing with a standard list named a, alongside a set of indices in a NumPy array called b. (Unfortunately, I cannot convert a into a NumPy array.) Is there a more efficient way to achieve the equivalent of "a[b]" without individually extracting ea ...

Fast method to verify variable existence in MySQL INSERT statement with PHP

I'm currently in the process of developing a PHP script that will allow users to add items to their shopping basket. Within my shopping basket table, I have fields for userid, product id, session id, notes, and various other details. Some of these fie ...

How to close an iframe with javascript or jquery?

I am working with a series of iframes on my website. I am trying to figure out how to close the last iframe in the list when a button is clicked. Can someone please provide guidance on how to achieve this? Specifically, I am looking to execute a window.cl ...

Printing a grid vector in C++: the ultimate guide

I am currently working on printing vectors in a grid using C++. My task is to populate a vector with random numbers in a 3x * 3y size and then display them as a two-dimensional matrix with a single array. I'm having trouble figuring out how to represe ...

Challenges encountered when redirecting users with a combination of javascript and php

I have a login form that triggers a JavaScript function upon submission. This function calls a PHP page to process the input. The issue I'm facing is with how the redirections are displayed based on the user's role type. It attempts to display t ...

The global variable remains unchanged within an ajax request

Here is the code I am working with: In developing this code, I referenced information about the window variable from here <script> $(window).on("load", function() { function myForeverFunc(){ ...

Using Angular to parse intricate JSON data

Need help parsing an http request in the following format: [ { "id": 1, "date": "2022-01-13T00:00:00.000+00:00", "time": "2022-01-13T21:21:21.000+00:00", "office&quo ...

Display the status in the textbox once a dropdown value has been selected

I have a function that allows me to add shops. Within this function, I am able to select whether the shop is OPEN or CLOSED. The goal is for the status of the shop, either OPEN or CLOSED, to appear in a textbox on another modal. When creating a user and ...

What are the best methods for capturing individual and time-sensitive occurrences within a service?

I am currently working on structuring the events within a service to enable a mechanism for subscribing/unsubscribing listeners when a controller's scope is terminated. Previously, I utilized $rootScope.$on in this manner: if(!$rootScope.$$listeners[& ...

How come my effort to evade quotation marks in JSON isn't successful?

When trying to parse a JSON-string using the JQuery.parseJSON function, I encountered an error message that read: Uncaught SyntaxError: Unexpected token R. This was unusual as the only uppercase 'R' in my JSON-formatted string appeared right afte ...

Another method to verify an input using HTML5 regex and JavaScript

When working with vanilla JavaScript to check an HTML input against a regex pattern, things can get tricky. I find myself going back to the parent element to validate the input, and while it works, it's not as elegant as I would like it to be. Here i ...

How can a JavaScript file interact with a backend without needing to specify the URL in the compiled code, thanks to webpack?

Currently, I am working on a React application with webpack. After compiling the code using the command webpack --mode production && webpack --config webpack.config.prod.js I utilize a .env.prod file to specify the variable REACT_APP_BASE_URL, wh ...

Promise.all does not wait for the inner Promise.all to complete before continuing

let dataObj = [ { Id: 1, name: 'Alice', Address:[{ city: 'Paris', country: 'France' }] }, { Id: 2, name: 'Bob', Address: [{ city: 'NYC', country: &a ...

I am having trouble getting the bootstrap link and css files to work on a specific URL. Can you please help me troubleshoot this issue and let me know if there are any additional files needed to

When attempting to apply the bootstrap link and css files to the URL "/list/:customListName", they are not working. However, changing the URL to "/:customListName" somehow makes it work. What is the reason behind this behavior and how can I properly style ...

Utilizing ng For in a personalized directive to fill a selection menu

I encountered an issue while trying to populate a selected dropdown using ngRepeat inside a custom directive. I came across this example that seemed similar to what I wanted to achieve here. Although it worked for the example, it didn't work for me. ...

implement a jQuery loop to dynamically apply css styles

Attempting to utilize a jQuery loop to set a variable that will vary in each iteration through the loop. The plan is for this variable to be assigned to a css property. However, the issue arises where every css property containing the variable ends up with ...

Confirming the browser exit on IE9

While searching on stackoverflow.com, I noticed an abundance of inquiries about a specific issue, but unfortunately, there doesn't seem to be a clear answer available. Apologies if this adds to the duplicate questions. In my Ajax-based web applicatio ...