What is the difference between the angular foreach and the javascript map function

Asked

Viewed 8,606 times

4

I would like to know the difference between using the angular.forEach and the function map javascript.

ex:

angular.forEach(meuArray, function(itens) {...})

meuArray.map(function(itens) {...});

2 answers

7


The map Javascript will only work in type values Array, because it is part of your prototype. That is, the map what you are referring to is Array.prototype.map.

Already the angular.forEach (which is a function available only when using the Angularjs framework) works both for Array as for Object.

The Array.prototype.map, additionally, returns mapped values for a new Array at the end of the iteration. Already the angular.forEach does not do this, it just runs (the returned value is the same past, no change).

In this example, a new array will be created:

var multipos_de_3 = [1, 2, 3].map(function (value) {
       return value * 3;
})

console.log(multipos_de_3);

Already in this, the values will be maintained

var retorno = angular.forEach([1, 2, 3], function (value, key) {

      return value * 3;
});

console.log(retorno);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

2

Actually both functions are from Javasscript. The difference between forEach and map is the functionality. forEach iterates all array values, while the map returns a new array as it has the mapping feature.

For example this object array:

[{ 'nome', 'João',
   'idade', 20
},{ 'nome', 'José',
   'idade', 30
}]

To get only the name of these objects, with forEach would be:

var nomes = [];
array.forEach(function(item){
  nomes.push(item.nome);
});

The same operation with map:

var nomes = array.map(item => item.nome);

Both will return the array:

['João', 'José']
  • -1. He is not talking about the forEach Javascript, and yes to angular.forEach.

  • What is the difference between the forEach angular to Javascript @Wallacemaxters?

  • My answer already says. It doesn’t exist forEach in Object javascript.

  • At this point you’re right. I didn’t notice that he’s referring to forEach implemented only at the angular. But I will leave my answer because I presented a basic difference the canonical implementation between the two. Thank you :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.