3

The order of my array always changes when i do a foreach loop. How can I keep the order of the array.

var array1 = [{id:1, name:'foo'},{id:2, name:'bar'},{id:3, name:'lol'}]

After i do a foreach and output it to a new array, the order sometimes changes

var array2 = [];

angular.forEach(array1, function(post) {
  //for brevity i'll just keep it simple
   var sample = {id:post.id, name:post.name};
   array2.push(sample);
});

//OUTPUT
var array2 = [{id:3, name:'lol'},{id:1, name:'foo'},{id:2, name:'bar'}]

My question is how can i iterate without changing the order.

5
  • What do you mean the array changes when you do a foreach loop? Are you getting the array from a web service? Commented Oct 26, 2015 at 7:04
  • yes im getting it from an ajax response but order is ALWAYS the same it just gets messed up after the foreach loop Commented Oct 26, 2015 at 7:08
  • @JLRishe i added the code Commented Oct 26, 2015 at 7:08
  • 3
    @e_mam106 If array1 is actually an array, then this should not be happening. Can you show us what the actual JSON response of your service looks like? Commented Oct 26, 2015 at 7:11
  • Doing it in the console without using angular's version of forEach seems to work fine. Is there a specific reason why you're using angular's over the typical one? Commented Oct 26, 2015 at 7:22

1 Answer 1

1

Iterating over an Array is guaranteed to be in order. This is not true of dictionaries. If you want to create a new array, you can simply do something like this:

var array2 = array1.map(function(post) {
    return {id: post.id, name: post.name};
});
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.