Home > Mobile >  reset index of map method javascript
reset index of map method javascript

Time:12-07

This is how I expected the result to be.

1 0
2 1
3 2
4 3
5 0
6 1
7 2
8 3
9 0
...
let arr= [];
for(let i=1; i<20; i  ) {
    arr.push(i)
}
function arrFunc() {
    arr.map((e,i) => {
    let index = i;
    if(index > 3) { 
        index = 0
        
    }
index  ;

console.log(e, index)
})
}

CodePudding user response:

You can use the remainder (%) operator on the index to get the desired output:

let arr= [];
for(let i=1; i<20; i  ) {
    arr.push(i)
}

for (let i = 0; i < arr.length; i  ) {
    console.log(arr[i], i % 4);
}

1 0
2 1
3 2
4 3
5 0
6 1
7 2
8 3
9 0
10 1
11 2
12 3
13 0
14 1
15 2
16 3
17 0
18 1
19 2

CodePudding user response:

For this specific case, you can use a modulus. Modulus 4, for the example you included.

const array = Array.from({length: 20}, (_,i) => (i 1)%4)

console.log(array)

  • Related