2

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?

morko
  • 17
  • 3
  • Are you just trying to sort `data`? – mwilson Sep 04 '18 at 23:09
  • 2
    No. But you could use [`Array` iteration methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Methods) like `forEach`, possibly using `reverse`. – Sebastian Simon Sep 04 '18 at 23:09
  • 2
    it's not efficient to do it that way, you would be better having two separate function with one loop in each. – Nicolas Sep 04 '18 at 23:12
  • Possible duplicate of [Sort array by firstname (alphabetically) in Javascript](https://stackoverflow.com/questions/6712034/sort-array-by-firstname-alphabetically-in-javascript) – Juan Sep 04 '18 at 23:35

1 Answers1

1

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.

Bergur
  • 3,962
  • 12
  • 20