Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

81
Views
How to add reverse number in an array

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
7 months ago · Juan Pablo Isaza
3 answers
Answer question

0

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);

7 months ago · Juan Pablo Isaza Report

0

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}

7 months ago · Juan Pablo Isaza Report

0

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();

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs