Course Content
Data types and Values
0/1
Object-oriented programming in JavaScript
0/1
Error handling and debugging in JavaScript
0/1
JavaScript functions for string and array manipulation
0/1
JavaScript Libraries and Frameworks
0/1
JavaScript
About Lesson

Array of Arrays in JavaScript

An array of arrays, also known as a “multidimensional array,” is a data structure that allows you to create an array where each element is itself an array.

Creating an Array of Arrays

You can create an array of arrays by placing arrays as elements within an outer array:

const arrayOfArrays = [
  ['apple', 'banana', 'orange'],
  [1, 2, 3],
  [true, false]
];

Accessing Elements

To access elements in an array of arrays, use multiple indices:

const innerArray = arrayOfArrays[0]; // ['apple', 'banana', 'orange']
const element = arrayOfArrays[1][0]; // 1

Iterating Through an Array of Arrays

Use nested loops to iterate through the arrays:

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

Use Cases

An array of arrays is useful for representing more complex data relationships, such as matrices, tables, and multi-dimensional data. It’s commonly used when you need to organize and work with structured data sets.


Practice with the following code; create a main.js file, then copy and paste every code from here to the end.

then execute/run the code by navigating to the folder with file in the console/terminal and type: node main.js

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

const questions = [
  {
    question: 'What is the capital of France?',
    options: ['London', 'Berlin', 'Paris', 'Madrid'],
    correctOption: 2
  },
  {
    question: 'Which planet is known as the Red Planet?',
    options: ['Venus', 'Mars', 'Jupiter', 'Neptune'],
    correctOption: 1
  },
  {
    question: 'What is the largest mammal?',
    options: ['Elephant', 'Giraffe', 'Blue Whale', 'Hippopotamus'],
    correctOption: 2
  }
];

let score = 0;

function displayQuestion(index) {
  const questionObj = questions[index];
  console.log(questionObj.question);
  questionObj.options.forEach((option, idx) => {
    console.log(`${idx + 1}. ${option}`);
  });
}

function promptUserForAnswer(index) {
  displayQuestion(index);
  rl.question('Enter the number of your answer: ', answer => {
    const userAnswer = parseInt(answer) - 1;
    if (userAnswer === questions[index].correctOption) {
      console.log('Correct!n');
      score++;
    } else {
      console.log('Incorrect.n');
    }
    if (index < questions.length - 1) {
      promptUserForAnswer(index + 1);
    } else {
      console.log(`Quiz completed! Your score: ${score} out of ${questions.length}`);
      rl.close();
    }
  });
}

console.log('Welcome to the Quiz Game!n');
promptUserForAnswer(0);