Home > database >  JavaScript for loop in reverse 5 times and get top 5 values only
JavaScript for loop in reverse 5 times and get top 5 values only

Time:03-07

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

  • Related