A guide on displaying multi-dimensional arrays and single-dimensional arrays together using a for loop

I have a coding challenge where I need to output a specific set of hobbies for each day of the week. The desired result is as follows:

My hobbies on Mondays are Poker, VideoGames

My hobbies on Tuesday are Board Games, Hiking, Rockclimbing

My hobbies on Wednesdays are Driving, Shopping

I've been trying to accomplish this using nested for loops, but I'm encountering some difficulties. While I can successfully list out the weekdays, I'm struggling to access and display all elements of the multi-dimensional hobbies array corresponding to each day.

Is there anyone who could provide guidance on how to achieve this?

var hobbies = ['Poker','VideoGames'];

              ['Board Games', 'Hiking', 'Rockclimbing'];

              ['Driving', 'Shopping'];

const weekdays = ["Monday", "Tuesday", "Wednesday"];

for (i = 0; i < 3; i++) {
console.log("My hobbies on", weekdays[i], "are ");
for (x = 0; x < 5; x++)
  console.log(hobbies[?]);
}

Answer №1

Here is the essential piece of code you've been searching for:

let passions = [['Skiing', 'Reading'],
               ['Painting', 'Cooking', 'Cycling'],
               ['Dancing', 'Photography']];

const workdays = ["Thursday", "Friday", "Saturday"];

for (i = 0; i < 3; i++) {
    console.log("My interests on " + workdays[i] + " include " + passions[i].join(', '));
}

Answer №2

Essentially, the process involves iterating through arrays to obtain the desired outcome.

var activities = [
  ['Skiing', 'Swimming'],

  ['Fishing', 'Cycling', 'Running'],

  ['Reading', 'Cooking']
];

const days = ["Monday", "Tuesday", "Wednesday"];

for (i = 0; i < activities.length; i++) {
  console.log("My activities on", days[i], "are "+ activities[i].join() );
}

Revised code for handling errors.

function getDayName(index){
    const days = ["Monday", "Tuesday", "Wednesday"];
    if(index < days.length){
      return days[i];
    }
    
    return 'X';

}

var hobbies = [
      ['Singing', 'Dancing'],

      ['Painting', 'Cooking', 'Gardening'],

      ['Writing', 'Shopping'],
      ['Drawing', 'Running']
    ];


    for (i = 0; i < hobbies.length; i++) {
      console.log("My hobbies on", getDayName(i), "are "+ hobbies[i].join() );
    }
    
    

Answer №3

There are numerous approaches to achieve this, but I recommend starting with a JavaScript course or a data structure course first.

While I could provide different solutions, I suggest editing your own code since you have a better understanding of it that way.

var hobbies_ = [
    ['Poker','VideoGames'],
    ['Board Games', 'Hiking', 'Rockclimbing'],
    ['Driving', 'Shopping']
];

var weekdays_ = ["Monday", "Tuesday", "Wednesday"];


for (i = 0; i < weekdays_.length; i++) {
    let day_hobbies ='';
    for (x = 0; x < hobbies_[i].length ; x++)
    {
        if(i == 0){
            day_hobbies += `${ hobbies_[x] }`;
            }else{
            day_hobbies += `, ${ hobbies_[x] }`;
        }

    }
    console.log("My hobbies on", weekdays_[i], "are ",day_hobbies);
}

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

Managing additional components in request JSON when communicating with DialogFlow, previously known as Api.ai

My current challenge involves enhancing the information sent in a JSON request from my application to DialogFlow. While I am familiar with triggering events to send data calling an intent through the method described in Sending Parameters in a Query Reques ...

What are the common reasons for jQuery Image Slider malfunctioning?

After following a tutorial on Youtube (https://www.youtube.com/watch?v=KkzVFB3Ba_o) about creating a JQuery image gallery, I realized that my implementation is not working at all. Despite carefully reviewing my code and fixing any errors I could find, the ...

Location of Ajax callback function

I encountered an issue with a callback function that was placed within $(document).ready. The callback function wasn't functioning as expected. Surprisingly, when I moved it outside of $(document).ready, the code started working flawlessly. I am puzzl ...

Error encountered: Unable to access the 'Lastname' property as it is undefined

Even though the console displays the value of $("#surname").val(), I am still encountering an error. Could it be that the script is executing before the form is dynamically built? $(function () { $("#addEmployeForm").submit(function (event) { ...

AngularJS triggers after the completion of Ajax requests

How can I implement AJAX within Angular AJAX? In my Angular setup, it looks like this: Index.html MyApp.controller('MainController', function($scope, $http, $location , $compile) { $scope.content_middle = 'Welcome'; ...

What is the process for plotting specific data points in MATLAB?

The X axis is set with values [2,6,10], and the Y axis ranges from [0.5,0.4,0.2,0.2,...0.5], all falling between 0 and 1. Each set of points corresponds to one-third for 2, another third for 6, and the final third for 10. The values for each point can ran ...

Unable to reach the sub-component of the JSON object that was returned

For some reason, I can't seem to access a sub object of a returned $Resource object that fetched a group of JSON objects. It's baffling me. Resource > $resolved: true > $then: function (b, g) {var j=e(),h= > data: Object > 519bc5f6 ...

Using Cache API for MVC Views

Creating a basic MVC form, I have been experimenting with the Javascript Cache API to store all my css, js, and html files. This way, even if users are in areas with unreliable internet access, they can still access my web form. In addition to IndexedDB an ...

Creating a calculator with JavaScript event listeners - easy steps to follow!

I'm currently working on a JavaScript calculator project and facing challenges in understanding how to create variables for storing targeted DOM elements, input/output values, and adding event listeners to retrieve data from buttons upon clicking. I ...

What is the best way to utilize AJAX for displaying data within a div element?

I am struggling with integrating two files - index.php and process.php. In my index.php file, there is a form that submits to process.php: <form class="form" action="process.php" method="POST" name="checkaddress" id="checkaddress"> <table> ...

Error: Unable to access the 'addLayer' property of an undefined object in the leaflet library

I have been working on inserting markers into leaflet.indoor using data from a geoJson file. However, I keep encountering the error message "Uncaught TypeError: Cannot read property 'addLayer' of undefined" in leaflet-indoor.js:57. As someone who ...

HTTP request in Angular with specific body content and custom headers

My goal is to access the sample API request from , as demonstrated in the documentation: curl -H "api-key: 123ABC" \ -H "Content-Type: application/json" \ -X POST \ ...

Setting default zoom level for Google Map in HTML

Initially, the map for the second city is hidden. When the second button is clicked, the map for the first city will be hidden and the map for the second city will be displayed. However, in this case, the map for the second city appears zoomed out. How can ...

Issue with jQuery's outerHeight() function persisting despite attempting to fix it with jQuery(window).load()

Once the content is loaded using AJAX, I need to retrieve the outerHeight of the loaded elements. Ajaxload file: $('#workshop').submit(function(event){ $.ajax({ url: URL, type: 'POST', data: $(' ...

Initiate animation on command with either Jquery or JavaScript

I have a special notification display box that showcases errors on my website .flash { height: 75px; position: fixed; top: 20px; right: 20px; z-index: 10; background-color: #ffffff; box-shadow: 0 0 30px 2px #dddddd; -webkit-animation: flas ...

Information bubble from HERE Maps -

Currently, I am integrating HereMap into my Vue.js application. You can find the code for implementing HereMap in Vue.js here. Next, I need to add an InfoBubble to this map using the code available here. However, I encounter a problem where the InfoBubbl ...

- Tips for preventing requests from being blocked in Node.js

Greetings! I recently crafted a straightforward Node.js server: const express = require('express') const app = express() app.use(express.json()) app.get('/otherget', (req,res) => { ...

Improve the looping mechanism to efficiently extract key values from an object and store them in an array

I am working with an object that contains various questions, each with a different difficulty level indicated by the "difficulty" property. I have implemented a for loop to sort the questions into categories based on their relative difficulty, such as easy ...

Filtering an array in Angular JS based on user input

My current issue revolves around creating a search input field with a search filter in an ng-repeat. I have successfully implemented the search input field, and now I am trying to figure out how to select all the items that match my search criteria using a ...

Pattern matching to find occurrences of their, their's, theirs, theirs, and theirs' using regular expressions

I am attempting to create a regex in JavaScript that matches the different forms of "their" and its possessive form. Currently, I have their|their(?:'?s), which successfully matches their, theirs, and their's; but does not match theirs'. C ...