I've been reading recently about Functional Programming and Immutable Objects in Javascript. What is the functional programming way of using map method?
Say I want to double values in an array. I can do:
var arr1 = [{a: 1}, {a: 2}, {a: 3}];
arr1.map(function(el){
el.a = el.a*2;
return el;
});
// arr1 => [{a: 2}, {a: 4}, {a: 6}]
But this seems to break the rules of functional porgramming and immutability the callback will modify directly elements of the array. Is the following the 'correct' way to do this?
var arr1 = [{a: 1}, {a: 2}, {a: 3}];
var arr2 = angular.copy(arr1);
var arr2 = angular.copy(arr1).map(function(el){
el.a = el.a*2;
return el;
});
arr1 = arr2;
// arr1 => [{a: 2}, {a: 4}, {a: 6}]
Or am I simply overthinking this? Fiddle is here.
But this seems to break the rules of functional porgramming and immutability.How? sincemapwill not modify the existing array, it will return a new one.el.a = el.a * 2will.var arr2 = arr1.map(el => el*2);arr1to be mutated, then simplyreturn el.a*2;and taking output inarr2will do the job.arr2 = arr1.map(el => {a:el.a*2})