[Vuejs]-How would I replicate nth-child in JavaScript

1👍

The easiest way to make it work is to use simple for instead of map().

function nthChild(array, startIndex, eachIndex) {
   let newArray = []
   for(let i = startIndex; i < array.length; i+=eachIndex) {
       newArray.push(array[i])
   }
   return newArray
}

So from CSS reference :nth-child(eachIndex*n + startIndex)

Here is an example:

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

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

Leave a comment