Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When/why to use map/reduce over for loops

Tags:

javascript

So I am getting into a bit of object manipulation in JavaScript for the first time and I have a question I'm wondering if anyone could answer.

When I have an object I want to manipulate I could do something to the extent of a few nested for loops, however there are functions built into JavaScript, like map/reduce/filter, and libraries like lodash/underscore.

I assume the latter (map/reduce/filter and the libraries) are better practice but I'm just curious as to why.

I am doing some pretty basic object manipulation that could be solved with a few well placed for loops to grab and change the right keys/values in the object, but can be easily done with the functions/libraries in JS. Just curious as to how they are better - like better performance/cleaner code/ease of use/whatever else.

Apologies, there is no code. I would very much appreciate anyone helping me understand more here.

Edit - so taking from the examples for map()

I could take the example for javascript.map

 var kvArray = [{key:1, value:10}, {key:2, value:20}, {key:3, value: 30}];
var reformattedArray = kvArray.map(function(obj){ 
var rObj = {};
rObj[obj.key] = obj.value;
return rObj;
});

I could do something like

   var kvArray = [{key:1, value:10}, {key:2, value:20}, {key:3, value: 30}];
var reformattedArray = [];

for(var object in kvArray){
  //combine both values into object inside of kvArray[object]);
 };

A lot less code - but any other benefits worth knowing about?


2 Answers

I know I'm replying to an old answer but just wanted to point out for future readers.

Map reduce and filter functions come from the functional programming world.

These are first class built-in operators in languages like Lisp, Haskell, and others(ml?). Functional languages tend to prefer to run operators over immutable data than make the code run over the data to operate on it (say loops). So they provide simpler but powerful interfaces like map, filter and reduce when compared to providing for and while loops.

It also helps them satisfy other requirements like immutability etc. That's why maps give u back a new map instead of mutating the old one. These are very good from a concurrency point of view, though they may be slower in certain contexts.

This approach usually leads to fewer errors in code in multi-threaded or high concurrency apps. When multiple actors act on the same piece of data, immutability helps keep code from stepping on each other's toes.

Since javascript tries to be partially functional by providing some functionalities of functional programming languages, it might have made sense to implement map, filter and reduce functions in it too.

YMMV depending on what you are doing with the tools you are given.

If your code works better with a for loop, go for it.

But if you ever find asynchronous code munching on common data and you end up splitting your hairs trying to debug a loop. Say hi, to map, reduce and filter.

like image 65
onkkno Avatar answered Sep 04 '25 21:09

onkkno


.map() allows you to create a new array by iterating over the original array and allowing you to run some sort of custom conversion function. The output from .map() is a new array.

var orig = [1,2,3,4,5];
var squares = orig.map(function(val) {
    return val * val;
});
console.log(squares);   // [1,4,9,16,25]

.reduce() allows you to iterate over an array accumulating a single result or object.

var orig = [1,2,3,4,5];
var sum = orig.reduce(function(cum, val) {
    return cum + val;
}, 0);
console.log(sum);    // 15

These are specialized iterators. You can use them when this type of output is exactly what you want. They are less flexible than a for loop (for example, you can't stop the iteration in the middle like you can with a for loop), but they are less typing for specific types of operations and for people that know them, they are likely a little easier to see the code's intent.

I have not myself tested the performance of .map() and .reduce() versus a for loop, but have seen tests for .forEach() which showed that .forEach() was actually slower in some browsers. This is perhaps because each iteration of the loop with .forEach() has to call your callback function, whereas in a plain for loop, you do not have to make such a function call (the code can be directly embedded there). In any case, it is rare that this type of performance difference is actually meaningful and you should generally use whichever construct makes clearer, easier to maintain code.

If you really wanted to optimize performance, you would have to write your own test case in a tool like jsperf and then run it in multiple browsers to see which way of doing things was best for your particular situation.


Another advantage of a plain for loop is that it can be used with array-like objects that support indexing, but do not support .reduce() and .map().

And, a for/of loop can be used with any object that implements the iterator protocol such as HTMLCollection.

like image 26
jfriend00 Avatar answered Sep 04 '25 23:09

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!