Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

118
Views
JavaScript for loop in reverse 5 times and get top 5 values only

I want to run the loop in reverse and I wat to only 5 top values like (16, 17, 18, 19, 20) but no mate how log is array

var arr = [
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
];

for (var i = arr.length - 1; i >= 5; i--) {
  console.log("=>", arr[i]);
}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You just need to sort total array by descending, then get the max 5 value and reverse them.

arr.sort((a,b) => b-a).slice(0,5).reverse()
about 4 years ago · Juan Pablo Isaza Report

0

You can reverse the array by calling reverse and after that use slice to get only 5 itmes, No need to rely on loop

let arr = [
  1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
];

let result = arr.reverse().slice(0,5);

console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

You could slice the array from the end, reverse and iterate the items.

const
    array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];

for (const item of array.slice(-5).reverse()) {
    console.log(item);
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!