morko
morko

Reputation: 17

About Javascript For Loop

what i want to do

if(data){
var loop = var i = 0; i < arr.length; i++; // ASC
} else { 
loop = var i = arr.length-1; i > -1; i--; // DSC
}

for(loop){ ..content.. }

How can I do something like this?

Upvotes: 2

Views: 75

Answers (1)

Bergur
Bergur

Reputation: 4057

If you're trying to sort the array, then check out .sort: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

const arr = [4, 2, 5, 1, 3];
const data = true;
    
if (data) {
  arr.sort((a, b) => a - b); // asc
} else {
  arr.sort((a, b) => b - a); // desc
}

console.log(arr)

If you want to loop through the array from the end instead of start, then check out .reverse: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse

const arr = [4, 2, 5, 1, 3];
const data = true;
    
if (data) {
  arr.reverse()
}

arr.forEach(item =>  {
  console.log(item)
})

In JavaScript you rarely use a standard for loop (though you can) and instead use iterators like .forEach, .reduce in combination with array functions like .reverse, .concat, etc.

Upvotes: 1

Related Questions