Home > Blockchain >  How to add reverse number in an array
How to add reverse number in an array

Time:03-30

How to add the reverse number in the array. I wanna add the number in reverse in the array.

var totalBidders = 22;
var NoOfWinners = 3;

var arr = [];
let e = totalBidders-NoOfWinners;
for (let i = totalBidders; i > e; i--) {
  console.log( "=>" , i);
  arr.push(i); 
  console.log(arr[i]);
}

But I got this :

index.js:484 => 22
index.js:486 undefined
index.js:484 => 21
index.js:486 undefined
index.js:484 => 20
index.js:486 undefined

CodePudding user response:

Just use Array.reverse

var totalBidders = 22;
var NoOfWinners = 3;

var arr = [];
let e = totalBidders - NoOfWinners;
for (let i = totalBidders; i > e; i--) {
  arr.push(i);
}
arr.reverse();
console.log(arr);

OR

Simply control the loop variables.

Sample Implementation

var totalBidders = 22;
var NoOfWinners = 3;

var arr = [];
let e = totalBidders - NoOfWinners;
for (let i = 1; i <= NoOfWinners; i  ) {
  arr.push(e   i);
}
console.log(arr);

CodePudding user response:

Another way, one-liner if you don't mind:

const totalBidders = 22;
const NoOfWinners = 3;

const arr = [...Array(NoOfWinners).keys()].map((e) => totalBidders - e);

console.log(arr);
.as-console-wrapper{min-height: 100%!important; top: 0}

CodePudding user response:

console.log(arr[i])

Will try to access the index 22, 21 & 20 values from an array arr but these indexes does not exist as arr.push(i) is pushing the 22, 21 & 20 as values at 0, 1 & 2nd index into an array.

If you want to access the values, You can try this :

console.log(arr[arr.length-1])

Demo :

const totalBidders = 22;
const NoOfWinners = 3;

const arr = [];
const e = totalBidders-NoOfWinners;
for (let i = totalBidders; i > e; i--) {
  console.log( "=>" , i);
  arr.push(i); 
  console.log(arr[arr.length - 1]);
}

arr.reverse();

  • Related