Friday, 13 June 2014

Javascript MapReduce tips and tricks

Recently I was using map and reduce functions in javascript for my project. both of them are absolutely amazing. You can use them for different kind of array manipulations. Here I am listing out various use cases with code.
1. Finding unique elements in an Array
var cities = ["bombay", "delhi", "bombay", "delhi", "delhi", "chennai"];

var uniqueCities = cities.reduce(function(p, c){
         if(p.indexOf(c)<0) p.push(c);
            return p;
         },[]);
console.log(uniqueCities); // ["bombay", "delhi", "chennai"]
2. Sum up array of numbers
var foo = [1,2,3,4,5];
var bar = foo.reduce(function(sum, a) { return sum + a; }, 0)
var barOne = foo.reduce( function(sum, a) { return sum + a; }, 1)
console.log(bar, barOne) // 16
here, the second argument of reduce is initial value of sum. If you don't give the second argument at all, it will work here but it may not work in case of complex objects.

...more use case coming soon.

No comments:

Post a Comment