Display an array comprising of other arrays

function PersonXYZ(fName, lName) {
this.lastName = lName;
this.firstName = fName;
this.grades = [];

this.grades.push([4, 67, 5]);
this.grades.push([41, 63, 5]);
this.grades.push([4, 67, 55]);
} 

var person = new PersonXYZ('John', 'Doe');


person.grades.forEach(function iterateArray(arr1, arr2) {
  arr1.forEach(function displayValue(val1) {
    console.log(val1);
  });
  arr2.forEach(function displayValue(val2) {
     console.log(val2);
  });
});

I encountered the Error: arrSch2.forEach is not a function

I am puzzled as to why arrSch2.forEach is not working properly. Isn't the second element of grades an array with the values [41, 63, 5]?

Answer №1

When it comes to the forEach function, the second parameter is the index. In this case, arrSch2 is simply a number and the forEach method does not apply to numbers.

Looking at it from a different angle:

peprson.marks.forEach(function callBack(arrSch1, index) {
    ...
}

Answer №2

The third value of the array is [13, 79, 8], however, this is not what is being passed in your parameters. If you simply wish to loop through the array, you can use code similar to the example below:

function PersonXYZ(fn, ln) {
  this.lastname = ln;
  this.firstname = fn;
  this.scores = [];

  this.scores.push([6, 81, 2]);
  this.scores.push([13, 79, 8]);
  this.scores.push([6, 81, 22]);
}

var individual = new PersonXYZ('Joe', 'Smith');

individual.scores.forEach(function (array) {
  array.forEach(function (num) {
    console.log(num);
  });
});

Answer №3

When using Array.prototype.forEach, the callback function requires three arguments:

  1. currentValue - Represents the current element being processed in the array.
  2. index - Indicates the index of the current element being processed in the array.
  3. array - Refers to the array to which forEach() is applied.

Note that arrSch2 is a number, not an array.

Below is the revised code that eliminates the second forEach call:

function PersonAMK(vn, ln) {
this.nachname = ln;
this.vn = vn;
this.marks = [];

this.marks.push([4, 67, 5]);
this.marks.push([41, 63, 5]);
this.marks.push([4, 67, 55]);
} 

var peprson = new PersonAMK('Unknwon', 'Unknown');


peprson.marks.forEach(function callBack(arrSch1) {
  arrSch1.forEach(function callBack(nod1) {
    console.log(nod1);
  });
});

Answer №4

Have you thought about employing a basic for loop for this task?

function PersonAMK(vn, ln) {
this.nachname = ln;
this.vn = vn;
this.marks = [];

this.marks.push([4, 67, 5]);
this.marks.push([41, 63, 5]);
this.marks.push([4, 67, 55]);
} 

var peprson = new PersonAMK('Unknwon', 'Unknown');

   for (i = 0; i < peprson.marks.length; i++) { 
      for (j = 0; j < peprson.marks[i].length; j++){ 
          console.log(peprson.marks[i][j]);    
      }
   }

Give this a try. Use the JSON.stringify() method to get the following output:

{"nachname":"Unknown","vn":"Unknwon","marks":[[4,67,5],[41,63,5],[4,67,55]]}
. Remember to iterate over peprson.marks as it contains arrays at each index. Best of luck!

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

Having Difficulty with Splicing Arrays in React?

Currently working on learning React and trying to develop my own mini-app. I'm basing it very closely on the project showcased in this video tutorial. I've run into an issue with the comment deletion functionality in my app. Despite searching va ...

The clash between React Inline styles and Client CSS can lead to conflicts in styling

Our application needs to be loaded into the client's page, which is built using React. We are implementing React Inline Styles by defining styles as objects. However, we have encountered an issue where any CSS specified by the client using tag attribu ...

How to fix jQuery animate queue issue so animations run at the same time

Previously, I successfully used the jQuery queue modifier for simultaneous animations. However, this time around, I am facing difficulties in getting it to work. You can view the issue on the following page: . When you click on "notifications" at the top ...

props remain undefined even after being assigned in the redux store

I encountered an unusual error related to a reducer called prs when adding or deleting a person in an app. Essentially, this app allows users to add or remove a person with a unique ID assigned to each individual. To start off, here is the parent componen ...

What is the process for incorporating an external script into my Vue methods?

After a user registers, I need to send them a confirmation email using vue.js. I am looking to implement the script provided by . How can I incorporate the "Email.send" method into my vue.js application? <script src="https://smtpjs.com/v3/smtp.js"> ...

Ways to switch visibility based on user's selection

Currently, I am working on a project that involves a select form with multiple options. However, I need to display a specific div only when a particular option is selected. Can anyone suggest the best solution for this scenario? Your guidance would be grea ...

"Encountering an issue with the Foreach function in nextjs when iterating through

I attempted to iterate through each character in a String, but the SPANS are not displaying. What could I be doing incorrectly? export default function Work() { const logoText = "The future starts here."; return ( <div className=& ...

What is the best way to design an angular directive or service specifically for straightforward pagination featuring only next and previous options?

Within a block of div tags, an ng-repeat directive is being used to display sets of 3 divs at a time. By clicking on the next button, the next set of 3 divs should be displayed, and the same goes for the previous button. Check out the HTML code below: &l ...

Vue.js parent component sending new data: prop mutation detected

Encountering an issue in the console with the following error message: Instead, use a data or computed property based on the prop's value. Prop being mutated: "sortType" Within my root file, I have an API and filter function sending data to comp ...

Embark on a journey through Express.js routes with a unique context

After grappling with this issue for a few days, my brain feels fried and I can't seem to find the most efficient solution. My ultimate goal is to be able to repeat a route journey with new context data at the start. For example: app.get('/test& ...

The Angular component is failing to display the template

After following a tutorial on UI-Router () I have implemented the following states in my Angular application: angular .module('appRoutes', ["ui.router"]) .config(['$stateProvider', '$urlRouterProvider', function($sta ...

Is JavaScript responsible for creating threads for non-blocking AJAX requests?

It is widely believed that JavaScript operates on a single-threaded model, but it has the ability to run asynchronously. One intriguing aspect is how this single-threaded model manages non-blocking AJAX requests. Consider a scenario where a non-blocking A ...

Identify if a process operates synchronously or asynchronously

Can you identify in node.js, with the help of a function, if a method is synchronous or asynchronous? I am interested in creating a function that achieves the following: function isSynchronous(methodName) { //check if the method is synchronous, then ...

Invoking a JavaScript function using jQuery's AJAX

I'm currently working with jQuery and Ajax. Within my MainFile, I have the following code: <html> <head> <script src="Myscript.js"> </script> <script type="text/javascript"> $(doc ...

Accessing getUserMedia within Internet Explorer 11 or utilizing MediaStream on IE 11

I am attempting to utilize the getUserMedia function in IE 11 with the help of the temasys plugin. However, IE does not support the MediaStream instance returned by getUserMedia. Below is a snippet of my code: import React from 'react' import { ...

Preventing loss of context in jQuery ajax when mixing HTML/JS and opening a <script> tag

I've encountered a situation where I'm using ajax to communicate with the backend, which is responding with a mix of HTML and JavaScript code. To load this content into a div, I'm using the html() function like so: $("#mydiv").html(ajaxRespo ...

"Using the selected option from a dropdown list to pass to a PHP file for autocomplete functionality

Although there is no error in the code, I am facing an issue where, after selecting an option from the brands dropdown, when I type in the product field, it passes "%" instead of the brand id (1, 2, or 3). Is there a way to modify the code so that it passe ...

Does AngularJS have a callback function for ng-bind-html-unsafe?

Is there a way to efficiently remove certain elements from the DOM after they have been added by this code snippet? <div ng-bind-html-unsafe="whatever"></div> I have created a function to remove these elements, but I am unsure how to trigger ...

Sliding Image Menu using jQuery

I am struggling with creating a menu using jquery mouseenter / mouseout effects. My goal is to have a small icon displayed that expands to the left and reveals the menu link when a user hovers over it. The issue I am facing is that the effect only works w ...

How can you simulate a 'click' event on the currently active tab of a jQuery tab?

Hey there, I'm trying to automate a tab click on my website when a form is submitted and the return is valid. Here's a snippet of the HTML code: <ul id="tabUL" class="tabs js-tabs same-height"> <li class="current"> <a ...