What is the difference of angle forEach and the map function of javascript

2

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

ex:

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

meuArray.map(function(itens) {...});
    
asked by anonymous 02.12.2016 / 14:52

2 answers

4

The map of Javascript will only work on values of type Array , because it is part of your prototype. That is, the% w_that you refer to is map .

Since Array.prototype.map (which is a function available only when using the AngularJs framework) works for both angular.forEach and Array .

The Object additionally returns values mapped to a new Array.prototype.map at the end of the iteration. Since Array does not do this, it only cycles (the value returned is the same last, unchanged).

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);

In this case, the values will be kept

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>
    
02.12.2016 / 14:55
1

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

For example this array of objects:

[{ '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);
});

Same operation with map :

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

Both will return the array:

['João', 'José']
    
02.12.2016 / 14:59