Returning reverse array of integers using JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a number and returns an array of elements containing all natural numbers from n upto 1.

Input

const num = 6;

Output

const output = [ 6, 5, 4, 3, 2, 1 ];

Example

Following is the code −

 Live Demo

const num = 6;
const reverseArray = (num = 1) => {
   num = Math.round(num);
   num = Math.abs(num);
   const res = [];
   for(let i = num; i > 0; i--){
      res.push(i);
   };
   return res;
};
console.log(reverseArray(num));

Output

[ 6, 5, 4, 3, 2, 1 ]
raja
Published on 17-Apr-2021 11:46:17
Advertisements