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?

4
  • Are you just trying to sort data? Commented Sep 4, 2018 at 23:09
  • 2
    No. But you could use Array iteration methods like forEach, possibly using reverse. Commented Sep 4, 2018 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. Commented Sep 4, 2018 at 23:12
  • Possible duplicate of Sort array by firstname (alphabetically) in Javascript Commented Sep 4, 2018 at 23:35

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.