0

I am trying to convert 5 to [5, 4, 3, 2, 1, 0]. It is working properly using for loop, here is my snippets,

function countDown(startNum) {
  let countDownArray = []
  for(let i = startNum; i >= 0; i-- ){
    countDownArray.push(i)
  }
  return countDownArray
}

console.log(countDown(5));
//expected output: [5, 4, 3, 2, 1, 0]

I am also trying to solve the problem using ES6, However, there is a bug, using the following snippets 0 is missing.

const values = [...Array(5)].map((_,i) => i+1);
console.log(values);
const reverseValues = [...values].reverse();
console.log(reverseValues);
// output [5, 4, 3, 2, 1]
// however expected output [5, 4, 3, 2, 1, 0]
// 0 is missing here

How can I solve this problem using ES6?

Mamunur Rashid
  • 1,095
  • 17
  • 28

1 Answers1

2

Problem

const values = [...Array(5)].map((_,i) => i+1);

You create an arry of 5 elements, then spread it in a new array, and then map every element to it's index + 1.

So if you have 5-elements array, thier indexes will be 0, 1, 2, 3, 4 you map them with +1, so they become 1, 2, 3, 4, 5.

Solution

To achieve your goal you should map array of 6 element to it's indexes without adding 1

Temoncher
  • 644
  • 5
  • 15