1

I have few records and i want to use foreach loop in controller

var values = [[{"code":"sd","description":"d"}],[{"code":"gh","description":"d"}]]

angular.forEach(values, function(value, key){
console.log(key + ': ' + value.code);
});

This is given an object in return as object containing inside of another array. Can someone suggest me how i can use foreach loop to get the code with this data.

4
  • Usevalue[0].code Commented Apr 30, 2016 at 15:48
  • but this will loop on first item only right ? Commented Apr 30, 2016 at 15:50
  • Yes, are there more than one objects inside nested array? Commented Apr 30, 2016 at 15:51
  • yes these are dynamic array. Is there any way to use index while iteration ? Commented Apr 30, 2016 at 15:52

3 Answers 3

2

You just do another foreach inside

var codeList = [];

angular.forEach(values, function(value, key){
  angular.forEach(value, function(item, key){
      codelist.push(item.code);
   });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Yes i was thinking same to put them in another array and then use further. But is there any other more efficient way to avoid 3 times using ForEach loop ?
That is the efficient way to solve it. it would be N = 1. You could use a flatten method but it would still be less effective.
2
var values = [[{"code":"sd","description":"d"}],[{"code":"gh","description":"d"}]]

for (var i = 0; i< values.length ; i++){
   for (var j = 0; j< values[i].length ; j++){
      console.log(values[i][j])
   }
}
  • The native for loop is around 90% faster than angular.forEach.

  • Also angular.forEach loop can't break on a condition match.

Comments

0

Extending the Array prototype, allows you to do some awesome array manipulation in functional programming style easily. The following code should help.

arr.flatten().select('code').forEach(function (code) { console.log('code: ' + code) })

First, you'd need to add these functions to your code.

Array.prototype.select = function (prop) {
   var arr = this;
   var ret = [];
   for (var i = 0; i < arr.length; i++) {
       ret.push(arr[i][prop]);
   }
   return ret;
}
Array.prototype.flatten = function () {
   var arr = this.valueOf();
   var ret = [];
   arr.forEach(function (item) {
       if (Array.isArray(item)) {
           item.forEach(function (itm) {
               ret.push(itm);
           });
       }
       else {
           ret.push(item);
       }
   });
   return ret;
}

If you like it, you should probably check out https://github.com/mykeels/ArraysJS There are a lot more functions like these there.

Comments

Your Answer

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