Traversing through pair of arrays simultaneously using forEach loop in JavaScript

I am trying to create a for loop that simultaneously iterates through two variables. One is an array named n, and the other, j, ranges from 0 to 16.

var n = [1,2,3,5,7,8,9,11,12,13,14,16,17,18,20,21,22];
var m = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];

m.forEach(k => {
    n.forEach(i => {
        console.log(i, k)
    });
};

The expected output should be:

1,0
2,1
3,2
5,3
(...)

However, the current loop iteration seems to repeat every number 17 times instead of sequentially pairing each element as intended.

Can someone help point out where the issue lies?

Answer №1

Utilize the second parameter provided by forEach, which represents the current index being iterated over:

n = [1,2,3,5,7,8,9,11,12,13,14,16,17,18,20,21,22];

n.forEach((element, index) => {
  console.log(element, index);
});

If you have two separate arrays to start with, in each iteration, access the [index] property of the other array:

var n = [1, 2, 3, 5, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 20, 21, 22];
var m = [0, 1, 2, 3, 4, 5, 6, 7,  8,  9,  10, 11, 12, 13, 14, 15, 16];

n.forEach((num1, index) => {
  const num2 = m[index];
  console.log(num1, num2);
});

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

I am looking to utilize React and Next.js to map my array from an object. The component is a function employing hooks

I am attempting to map an array within an object and encountering some challenges. The structure of the object is as follows: const data = {data: (6) [{…}, {…}, {…}, {…}, {…}, {…}], page: 2, per_page: 6, total: 12, total_pages: 2} I have been ...

What is the best way to apply a CSS class to elements in a Vue.js template when using a v-for

Is there a way to dynamically name my td class after the step in this particular scenario? <td v-for="step in item.steps" :class="step.name"> {{ step.name }} </td> Currently, the class is being assigned as "item.steps.name" instead of taking ...

Utilizing ionic-scroll for seamless movement and scrolling of a canvas element

I have set up a canvas element with a large image and I want to enable dragging using ionic-scroll. Following the provided example: <ion-scroll zooming="true" direction="xy" style="width: 500px; height: 500px"> <div style="width: 5000px; h ...

Modifying an object using setState in React (solidity event filter)

Is it possible to update an object's properties with setState in React? For example: this.state = { audit: { name: "1", age: 1 }, } I can log the event to the console using:- myContract.once('MyEvent', { filter: {myIndexedParam: ...

Encountering an error while trying to run the command "npm run start" due to an issue of "EMFILE

After running npm update, my project start broke. When I try to use npm run start, it returns the following error: 10% building 0/1 entries 0/0 dependencies 0/0 modulesnode:internal/errors:484 ErrorCaptureStackTrace(err); ^ Error: EMFILE: too many ...

Set up webpack on your Mac using npm

Seeking help to install webpack using npm: sudo npm install -g webpack The following error message is encountered: node-pre-gyp WARN Using needle for node-pre-gyp https download node-pre-gyp WARN Pre-built binaries not installable for <a href="/cdn- ...

Vue Js image loading issue

I'm having trouble referencing an image to display in my view. I keep getting this error message: "InvalidCharacterError: Failed to execute 'setAttribute' on 'Element': 'product.images[0].filename' is not a valid attribut ...

Is there a way for me to create a link that is specifically for printing on 3D printers, rather than a link for downloading the

I have a project with a company that sells 3D printable models (.STL) online. They want to add specific models to their digital inventory without allowing direct downloads. Instead, once a customer purchases a model, they should be able to immediately pr ...

How to retrieve a string from a regular expression in Javascript without [Object object] output

Within my code, there exists a parent form component and a child component used for auto-completing text input. The Parent component passes an array of objects named autoCompTxt, consisting of name and id fields, to the Child component. //Parent: const [ob ...

Utilize data obtained from an ajax request located in a separate file, then apply it within a local function

Seeking assistance in navigating me towards the right path or identifying my errors. Pardon if my explanation is unclear, please be gentle! Currently, I am engaged in developing a function that executes an ajax call with a dynamically generated URL. The o ...

The type 'function that takes in a CustomEvent and returns void' cannot be assigned to a parameter of type 'EventListenerOrEventListenerObject'

When I upgraded from TypeScript version 2.5.3 to 2.6.1, my custom event setup started giving me an error. window.addEventListener('OnRewards', (e: CustomEvent) => { // my code here }) [ts] Argument of type '(e: CustomEvent) => vo ...

Accessing the i and i+1 elements within a ng-repeat iteration

I'm currently learning Angular and struggling with a seemingly simple issue. My goal is to achieve the following HTML structure in AngularJS: <div> <div> {{bar[i]}} {{bar[i+1]}} </div> <div> {{bar[i+2]}} ...

Guide on transforming Div content to json format with the use of jquery

I am trying to figure out how to call the div id "con" when the export button is clicked in my HTML code. I want it to display JSON data in the console. If anyone has any suggestions or solutions, please help! <html> <div id ="con"> < ...

Attention: It is not possible to update the React state on a component that is not mounted. Please use the useEffect cleanup function

Can you assist with solving this issue? //ReviewProductDetail.jsx : Initially, the page was populated from this particular component import React, { useEffect, useState } from 'react'; import RatingCardProductDetail from '../../components ...

Guide to aligning a v-combobox horizontally within a v-col alongside text in vuetify

Can anyone help me with aligning two v-col elements horizontally, where one of the columns contains a v-combobox? <div id="app"> <v-app> <v-container class="indigo lighten-5"> <v-row no-gutters> ...

Is there a way to update the value of a variable with the help of a checkbox?

When I check the checkbox, the specOrder const gets updated as expected. However, I am struggling to figure out how to remove the value when the checkbox is unchecked. Below is the code I have been working on: const SpecialtyBurgers = () => { cons ...

Unable to select image inside linked container

I'm attempting to display a dropdown menu when the user clicks on the gear-img div using jQuery. However, because it's wrapped inside an a tag, clicking redirects me to a URL. I also want the entire div to be clickable. Any suggestions for a solu ...

Webpack Is Having Trouble Parsing My JavaScript Code

I recently started using webpack and I'm struggling to get it to work properly. I haven't been able to find anyone else experiencing the same issue as me. Every time I attempt to run "npm run build" to execute webpack, I encounter this error: ER ...

Ways to smoothly conclude a loading animation in real-time

I have a unique challenge of creating a loading animation using Adobe After Effects instead of CSS. The main goal is to develop an animation that continuously loops, but when the loading process stops, it ends with a distinct finishing touch. For instance, ...

Activate video playback when scrolling, but ensure it only occurs one time

I've encountered an issue with my script that is meant to play a video when it reaches a certain position on scroll. The problem is, if the video is paused and scrolling continues, it starts playing again. I attempted to use just one scroll function b ...