Javascript loop woes

I have a number array ranging from 1 to 20. My goal is to create a loop that extracts every nth element from the array, starting with (1, 6, 11, 16). After the initial loop, it should then extract every 5th element, starting from 2 (2, 7, 12, 17).

My attempt:

const row = 5;

const cellArray = [
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
];

const newArray = [];

for (let i = 0; i <= row; i++) {
  cellArray.forEach((item, k) => {
    if (k === i) {
      newArray.push(item);
    }

    console.log(i);

    if (k % (row + i) == 0 && k !== 0) {
      newArray.push(item);
    }
  });
}

Output:

[1, 6, 11, 16, 2, 7, 13, 19, 3, 8, 15, 4, 9, 17, 5, 10, 19, 6, 11]

Expected Output:

[1, 6, 11, 16, 2, 7, 12, 17, 3, 8, 13, 18, 4, 9, 14, 19, 5, 10, 15, 20]

Answer №1

Your current approach seems unnecessarily complicated with the two separate checks you have implemented.

To simplify, you can just check if the item index k modulo 5 (representing the row) matches the value of i, then add the item to your result array.

const row = 5;

const cellArray = [
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
];

const newArray = [];

for (let i = 0; i <= row; i++) {
  cellArray.forEach((item, k) => {
    if (k % row === i) {
      newArray.push(item);
    }
  });
}

console.log(JSON.stringify(newArray))

Answer №2

Check out my solution below where I utilized a classic nested for loop.

const rows = 4;
const data = 
  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
const outputArray = [];

for (let i = 0; i < rows; i++) {
  for (let j = i; j < data.length; j += rows) {
    outputArray.push(data[j]);
  }
}

console.log(outputArray);

Answer №3

Another method that can be used is Array::reduce():

const row = 5;

const cellArray = [
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
];

const newArray = Array.from({length: row})
  .reduce((r, _, i) => (cellArray.forEach((item, k) => k % row === i && r.push(item)), r), []);

console.log(JSON.stringify(newArray))

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

Making If Statements Easier

Currently, I'm tackling an assignment that involves utilizing if statements and switch statements. Here is a snippet of code that I am working on: if (validateField(document.forms[0].name) == false) { isValid = false; } if (validateField(docume ...

Leveraging retrieved API data to generate numerous components

Hey there! I'm new to JavaScript and I'm working on creating a todo list with fake ToDos from jsonplaceholder using Fetch. My goal is to fetch five different ToDos and display them in separate list items within my list. However, I'm encounte ...

React- The Autocomplete/Textfield component is not displaying properly because it has exceeded the maximum update depth limit

My autocomplete field is not displaying on the page even though I wrapped it with react-hook-form for form control. When I check the console, I see this error: index.js:1 Warning: Maximum update depth exceeded. This can happen when a component calls setSt ...

What is the best way to include a file attachment using a relative path in Nodemailer?

I am currently utilizing the html-pdf converter plugin to transform an HTML page into a PDF file. After conversion, this plugin automatically saves the PDF to the downloads folder. When I attempt to attach a PDF to a nodemailer email, my code looks someth ...

What is the purpose of having a constructor in Typescript when an interface is already used for a class?

Is it necessary to have a constructor in my class if the class already implements an interface? It seems like redundant code to me. interface PersonInterface { firstname: string; lastname: string; email: string; } class Person implements Pe ...

An HTML document may display a segment of a URL

Is there a way to display part of a URL in an HTML document, so that if the URL changes, the corresponding content in the body also updates? For instance, www.example.com/?key=i - Is it possible for this link to be dynamically displayed within the body o ...

Make sure to include the onBlur and sx props when passing them through the slotsProp of the MUI DatePicker

This DatePicker component is using MUI DatePicker v6. /* eslint-disable no-unused-vars */ // @ts-nocheck import * as React from 'react'; import { Controller } from 'react-hook-form'; import TextField from '@mui/material/TextField&a ...

React - The ._id received by the Modal inside the map function is incorrect

My map is generating edit and delete buttons. The delete button requires confirmation, so I implemented a modal. When I use console.log(additive._id) on the first delete button, I get the correct ._id, but when I click the confirm button inside the modal, ...

JavaScript allows for the manipulation of elements within a webpage, which includes accessing elements from one

There is a file that contains a fragment for the navbar. The idea is to have listItems in the navbar, and upon clicking on those listItems, another subnavigationbar should open below it. Below is the code I currently have: <!DOCTYPE html> <html x ...

Angular Firebase Count of Items in List

My current dilemma revolves around obtaining a count of items within a firebase list. Firebase details: foods randompushid title: apple, comboQuery: apple23523526(userid) Angular Code snippet: this.foods= this.firebaseDB.list(& ...

Secure your website against XSS attacks with DOMPurify

Currently I am working on resolving a cross-site scripting (XSS) vulnerability using DOMPurify. The issue lies in the URL provided below: https://stage-xyzmysite.com/login/?rUrl=javascript:alert('hi'). In order to create a proof of concept, I am ...

Circular reference in Angular/TypeScript

I encountered a circular dependency issue in my Angular project and tried various solutions, including exporting all dependent classes from a "single file" as suggested here. Unfortunately, this approach did not work for me. I then explored other solutions ...

Ways to obtain the coordinates that surround a particular x, y location

I am trying to figure out how to generate an array of coordinates around a specific x, y point. For instance: xxxxx xxoxx xxxxx In this case, "o" is located at coordinates 3, 2. Now I aim to produce: xxx xox xxx as the set of coordinates surrounding "o ...

AngularJS login form with JSON data

I am currently learning Angular and focusing on the login form implementation. The specific model I am working with can be found in this PLNKR. There are two challenges that I am struggling to resolve. Issue 1: I'm trying to figure out how to tur ...

Is it possible to replicate an HTML table using JavaScript without including the headers?

Discover a JavaScript snippet in this stack overflow post that allows you to create a button for automatically selecting and copying a table to the clipboard. When pasting the data into an Excel template, my users prefer not to include the header informat ...

Attempting to retrieve the name of my controller and action within a JavaScript file

After checking out the Stack Overflow link here, I came across a suggested solution: var controllerName = '@ViewContext.RouteData.Values["Controller"].ToString()'; However, despite implementing this code in my JavaScript file, it does not yield ...

Retrieve the value of a JSON string

I'm having trouble accessing a json value in this example. No alert is being produced. Can you help me figure out what the problem is? This is the JSON data I am working with: { "response": [ { "id": "0", "elementName": "osname", "isEqual": t ...

You can definitely invoke a function within a React hook

This code snippet showcases a component utilizing Hooks in React Native import React, { useEffect, useState } from 'react'; import { StyleSheet, Text, View, TouchableOpacity, Animated } from 'react-native'; import CAStyles fro ...

Uploading files asynchronously in Internet Explorer 8

Currently, I am on the lookout for sample code that allows asynchronous file uploads in IE8 using Ajax. While having upload progress would be a bonus, it is not essential. Moreover, I specifically need PHP code to handle the uploaded files on the server ...

What are the steps to execute a module designed for NodeJS v6 LTS ES2015 in Meteor 1.4.x?

While I understand that Meteor includes NodeJS as a dependency, I'm facing an issue with a module written in ES6 that has a default argument value set within one of the Class methods. The problem arises when using Meteor v1.4.3.2: (STDERR) packages/m ...