What is the best way to recreate the functionality of nth-child in JavaScript?

In my current project, I'm attempting to replicate the functionality of CSS using JavaScript. Specifically, I am working with an index of items in a mapped array and assigning each item a unique index number.

computed: {
        parsedItems() {
            return this.items?.map((obj, index) => {
                return {
                    ...obj,
                }
            })
        }
    }

To provide some context for why I am pursuing this approach, I am creating a grid layout consisting of blocks containing various data such as images, titles, URIs, and text. I aim to implement the equivalent of :nth-child(7n + 1) in CSS using Vue 2 framework but with JavaScript.

The parsed items in the array contain images which are utilized by a custom component designed to handle image-related tasks, including setting the aspect ratio based on the height-to-width ratio of each image.

After researching how the :nth-child selector works in CSS,

:nth-child(3n + 3)

Essentially translates to:

(3 x 0) + 3 = 3 = 3rd Element
(3 x 1) + 3 = 6 = 6th Element
(3 x 2) + 3 = 9 = 9th Element
etc.

In my attempt to achieve this functionality in JavaScript, I initially tried multiplying the index by 7 and adding values from 1 to 7 accordingly:

computed: {
        parsedItems() {
            return this.items?.map((obj, index) => {
                return {
                    ...obj,
                    aspectRatio:
                        7 * index + 1 === 1
                            ? someAspectRatio
                            : 7 * index + 2 === 9
                                ? someAspectRatio
                                ...etc
                }
            })
        }
    }

However, this approach did not produce the desired results as the map method does not reset at every 7th element and the math calculation was off.

Subsequently, I experimented with the modulo operator (%) to improve the implementation:

computed: {
        parsedItems() {
            return this.items?.map((obj, index) => {
                return {
                    ...obj,
                    aspectRatio:
                        index % 7 === 0
                            ? someAspectRatio
                            : index % 3 === 0
                                ? someAspectRatio
                                : index % 2 === 0
                                    ? someAspectRatio
                                    : someAspectRatio
                }
            })
        }
    }

While this second attempt was more promising, it still fell short as the modulo results became mixed up with increasing numbers of items in the array.

Answer №1

If you want to simplify things, consider using a basic for loop instead of the map() function.

function grabEveryNth(array, startingIndex, interval) {
   let newArr = []
   for(let i = startingIndex; i < array.length; i+=interval) {
       newArr.push(array[i])
   }
   return newArr
}

Instead of dealing with complex CSS selectors like

:nth-child(eachIndex*n + startIndex)
,

Let's look at an illustrative example:

let numbers = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
grabEveryNth(numbers, 3, 3)

output: (6) [3, 6, 9, 12, 15, 18]

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

What can I do to resolve the issue of my Navigation Bar being blocked by a Javascript map?

My navbar creates a dropdown menu when I hover over it, but the map generated with the script tag blocks it. Here is the current setup: // JavaScript Document //This will make the navigation bar responsive. function myFunction() { var x = document.ge ...

Issue with pre-selected checkboxes: JavaScript

A function was created to automatically check the first value of a checkbox when a page is loaded: function defaultCheck(){ document.checkBoxForm.list[0].checked = true; var val=document.checkBoxForm.list[0].value; showtotal[0] = docum ...

What is the process of connecting a Yarn module to a Docker container in another repository?

I'm currently facing a challenge in linking a module to a Docker container from another repository. To provide some background, I have a container hosting a React application named launch-control-admin. This project relies on a yarn module called @com ...

CORS blocked the HTTP request due to the absence of the Access-Control-Allow-Origin header, although the header is actually present

Recently, I encountered an issue while working on a project using Python with Flask. I had created a REST API and needed my Vue app to interact with it and fetch data. However, I kept receiving an error message stating "No 'Access-Control-Allow-Origin ...

Steer Your Way: How to Redirect to a Different Router or Middleware in Node.js and Express.js

I'm creating an application using VENoM stack, and I have set up some middleware in the API like this: const express = require('express'); const router = express.Router(); require('./routes/orderRoutes')(router); require('./ ...

Potential null object detected when using a ref(null)

After reading the Vue Composition API documentation, it seems I should be utilizing ref(null) within a sub-component located inside <template>...</template>. Within this sub-component, there are methods such as open(), and my current approach ...

What are the different techniques for implementing React-Redux? Comparing Redux-thunk and Redux-Saga

My understanding of Redux is still quite hazy as I delve into various techniques and methods. I am curious to learn about other methods similar to redux-Thunk and redux-saga. Each utilizes distinct functions such as CreateSlice. I am interested to know w ...

Issue: The module 'xdl' cannot be located while executing the command "npm start" in React Native

Recently, I delved into learning React Native through an online Udemy course. Everything was going smoothly until a few days back when I encountered an error message after running the simple "npm start" command. Despite trying various solutions like reinst ...

Maintaining state value during client-side navigation in NextJs with Next-Redux-Wrapper

Currently, I am working on resolving the hydration issue that occurs when using wrapper.getServerSideProps. The problem arises when I reroute with the existing setup and the store gets cleared out before adding new data. This leads to a blank page as essen ...

Error: Unable to initialize VueRouter as a constructor

In my app.js, I have the code snippet below: const routes = [ {path:'/home', component:home}, {path:'/department', component:department}, {path:'/employee', component:employee} ] const router = new VueRouter({ ...

Reducing the length of Javascript code

Recently, I have been working on a project where I needed to use a piece of Javascript code to insert text into an input element when its label is double-clicked. $(document).ready(function() { $('#name-label').dblclick(function(){ $ ...

Guide to launching a Vue.js app on IIS within a Virtual Directory

When deploying my Vue.js application on IIS using a virtual directory, I encountered a challenge where I had to modify my routes to include the virtual directory name. Originally, my routes looked like this: export const routes = [ { path: '&apo ...

Could someone kindly provide a detailed explanation of this Javascript code, breaking it down step

I'm currently learning Javascript and stumbled upon this code snippet. However, I'm having trouble grasping its functionality. Can someone please break it down for me step by step? var ar1 = [1, 5, 6, 4, 3, 5, 100, -20]; function funDo(ar) { ...

Tips for handling tasks with javascript in mongodb

The Mongo database is set up with a sharding structure of 3 Shards named TestSharding. Additionally, the script for this configuration can be written in JavaScript. I am tasked with developing a program that identifies whether a file is in .json or .csv f ...

Creating a Redirect Form that Directs Users to a Specific Page Depending on Input Data

Apologies if this is a basic issue, but I'm struggling to figure it out. I am trying to create a form field on a webpage that will redirect users to a specific page based on the data they input. For example, if someone types in "dave" and submits the ...

Is there a way to optimize the re-rendering and redownloading of images files in map() when the useState changes? Perhaps we can consider using useMemo

This Chat application is designed with channels similar to the Slack App. Currently, I am utilizing a map() function for filtering within an array containing all channel data. The issue arises when switching between channels, resulting in re-rendering and ...

Importance of value attribute in <input ng-model ..>

Maybe a silly inquiry, but I'm curious about the purpose of having value="" in this particular situation: <input ng-model="something.name" value="" class="input-xlarge" /> Are there any alternatives to keeping the value attribute empty? I init ...

What are the best ways to display nicely formatted JSON data in a text area using React JS?

I am new to React JS and encountered an issue with rendering the pretty JSON data inside a textarea. I'm unsure which part of my code is incorrect, but I want my pretty JSON to be displayed within the textarea as shown below. "email":"<a href="/cd ...

Verify record removal without a PHP click

My website features a navigation menu that streamlines the browsing experience: <form action="../"> <select onchange="window.open(this.options[this.selectedIndex].value,'_top')"> <option value="" selected="selected">Navigate< ...

Is there a way to collapse just one specific row in Angular?

I am struggling to toggle only the selected row, any suggestions? Take a look at my code and demonstration here: https://stackblitz.com/edit/test-trainin-2-gv9glh?file=src%2Fapp%2Fapp.component.scss Currently, all rows are being toggled when clicked, but ...