Loop through the elements of one array using the indexes from a second array

Hey there! I need help with the following code snippet:

let names = ["josh", "tony", "daniel"];  
let arrayplaces = ["30", "60", "90"];

names.forEach((elem, indexed) => {
  const num2 = arrayplaces[indexed];
  console.log('The user ' + elem + ' iterated in place ' + num2);
});

I'm trying to iterate through each element of the first array and pair it with each element of the second array sequentially. The goal is to output all possible combinations.

Expected Output Example:

The user josh iterated in place 30
The user tony iterated in place 30
The user daniel iterated in place 30

The user josh iterated in place 60
The user tony iterated in place 60
The user daniel iterated in place 60

The user josh iterated in place 90
The user tony iterated in place 90
The user daniel iterated in place 90

If you have any idea on how to achieve this, please let me know!

Answer №1

To achieve this, you can nest loops for both arrays.

let names = ["josh","tony","daniel"];  
let arrayplaces = ["30", "60", "90"];

arrayplaces.forEach((element)=> {
  names.forEach((elem) => {
  console.log('The user ' + elem + ' iterated in place ' + element);
  });
 console.log('');
});

Answer №2

To go through every element in the arrayplaces array with each name, you will need two nested loops.

const names = ['josh', 'tony', 'daniel'];
const arrayplaces = ['30', '60', '90'];

names.forEach((elem, indexed) => {
  names.forEach((elem2) => {
    const num2 = arrayplaces[indexed];
    console.log(`The user ${elem2} iterated in place ${num2}`);
  });
});

Answer №3

To accomplish the task, make sure to iterate through both arrays.

for (let place of arrayplaces) {
    for (let name of names) {
        console.log(`The user ${name} visited place ${place}`)
    }
    console.log('\n')
}

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

Guide on transforming a JSON string into an array of custom objects using the json2typescript NPM module within a TypeScript environment

I am looking to utilize the json2typescript NPM module to convert a JSON string into an array of custom objects. Below is the code I have written. export class CustomObject { constructor(private property1: string, private property2: string, private p ...

wordpress widget that triggers a function when a click event occurs on jquery

I'm facing an issue where this function works perfectly in my header, but seems to have no effect when used in a widget $("#myID").click(function(){ var name = $("#name").val(); var phone = $("#phone").val(); console.log(name +" "+ phone) ...

Associating user input information with an AngularJS object

Currently, I am working on a project that involves inputting a user's ID, first name, and last name. Once the input is received, a user object is created and stored inside the logins array. My goal is to display each new user as the next item in an u ...

PHP's mechanisms for iterating through collections and storing vast amounts of

Recently, I've been working with some PHP code that scrapes a website to extract item information along with their prices. However, I've encountered an issue where I can't properly join the items and prices together as intended. item 1 pric ...

Creating an interface that accurately infers the correct type based on the context

I have an example below of what I aim to achieve. My goal is to start with an empty list of DbTransactInput and then add objects to the array. I experimented with mapped types to ensure that the "Items" in the "Put" property infer the correct data type, w ...

Preventing autocomplete from filling in empty password fields (React.js)

Once the browser autocompletes my login form, I notice that the password input's value is initially empty. However, when I click on the password field, suddenly the value appears. Additionally, there are several inexplicable events being triggered by ...

What is the best way to retrieve all records from a MongoDB collection?

I am currently delving into the realm of JavaScript and MongoDB while attempting to construct a basic blog engine. My goal is to retrieve all blog posts stored in MongoDB so that I can utilize this data to populate an EJS template. Although I successfully ...

"Enhance Your Sublime 3 Experience with a Jade Syntax Highlighter, Linting, Auto Complete, and

After trying out the recommended packages for Sublime Text, I'm still not satisfied with how they handle syntax highlighting, code linting, and auto suggestion. Could anyone recommend a comprehensive package specifically for Jade? ...

Using ng-style to apply a background image with a dynamic id

Hey there, I'm facing an issue here. The link provided below seems to not be working properly. Even though the id is set correctly within the scope, it seems like there might be a parsing error occurring. Any thoughts on what might be causing this pro ...

Extracting the magnifying glass from the picture

After implementing a function to add a magnifying glass (.img-magnifier-glass) on button click, I am now looking to remove the glass by clicking the "cancel" button. However, I am unsure of how to write this function to interact with the "magnify" function ...

Accessing JSON data model from Ember route or controller

Exploring the capabilities of Ember.js Is it possible to expose my data model as JSON through a route or controller? The object saved in the store looks like this: this.store.createRecord('Person', { id: 1, name: this.get('name'), ...

Sending AJAX data from VIEW to CONTROLLER in PHP (MVC) using AJAX: A step-by-step guide

I have a page at http://visiting/blog. The Controller contains two methods: action_index and add_index. When Action_index() executes, it returns pages with indexes. On the other hand, Add_index() invokes a model's method called add_data(), which inse ...

Having trouble resolving a component from a component library while utilizing NPM link

My React application is set up with Create React App and a separate component library. I'm currently experimenting with using 'npm link' to test changes in the component library directly on my local machine. To achieve this, I first run &ap ...

Utilizing a captured group from a regular expression as a key in replacing a string

Looking for help understanding the behavior displayed in this NodeJS 12 console code snippet. I'm attempting to replace a portion of a string with the result from a capture group. While it does work, using that capture group result as a key in an obje ...

Is there a way to modify the CSS display property upon clicking a link or button?

I have a ul with the id of "menu-list". The display property is set to "none" in my CSS file, but I want it to switch to "flex" when a link is clicked. I am trying to use the click event on the link to change the display prop ...

Developing a side panel for navigation

My goal is to create a sidebar that shifts to the right from the left side and makes space on the page when the hamburger menu is pressed. I have made progress in achieving this, but I am encountering difficulties with the animation. const btnToggleSide ...

Encountered an error while trying to set up the route due to Router.use() needing

Within my app.js file, I have the following code: app.use('/', require('./routes')); //old routes app.use('/api', require('./api')); Additionally, I have an api folder containing an index.js file. This is what the ...

JavaScript Bug Report

Currently, I am immersed in a project that encompasses various languages like HTML, JS, and PHP. While working on one of the PHP functions, I stumbled upon an unexpected anomaly. To dissect it better, I decided to break it down into simpler functions: &l ...

Retrieve a JSON array using an HTTP Get request in JavaScript (with jQuery)

I’ve been experimenting with various code snippets in an attempt to reach my objective, but so far I haven’t found a solution. Objective: My goal is to retrieve a JSON array of objects from a specific web URL using the GET method. This task needs to b ...

How to remove the initial negative value present in an array using C#

I have searched for various solutions, but none of them effectively address my requirement to eliminate the initial negative number in a sequence while retaining the others (there may be several negative numbers in the array). ...