Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep Array order when doing a foreach loop in Angularjs

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.

like image 264
edmamerto Avatar asked Jun 11 '26 00:06

edmamerto


1 Answers

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};
});
like image 157
Hunan Rostomyan Avatar answered Jun 13 '26 05:06

Hunan Rostomyan