alex
alex

Reputation: 7601

How to make the index go in countdown fashion in a map() loop?

This:

Array(12).fill().map((_, i) => {
  console.log(i)
})

Produces this:

0
1
2
3
4
5
6
7
8
9
10
11

How to change the loop so I get:

11
10
9
8
7
6
5
4
3
2
1
0

EDIT: I tried this:

Array(12).fill().reverse().map((_, i) 

But I'm still getting the index in the same order.

Upvotes: 0

Views: 79

Answers (1)

kakamg0
kakamg0

Reputation: 1096

You could try subtracting the index from length of the array like this:

const array = Array(12).fill()
array.map((_, j) => {
  console.log(array.length - j - 1)
})

Or this:

Array(12).fill().map((_, i, array) => {
  console.log(array.length - i - 1)
})

Upvotes: 1

Related Questions