Some Possible Uses of Array.prototype.reduce()

Some Possible Uses of Array.prototype.reduce()

Math Functions

var arr = [7,2,3,4];
var total = arr.reduce(function(previous, current, idx){
    return previous + current;
}, 4); 
//total = 20  

String Manipulation

var words = ["hello", "world"];
var phrase = words.reduce(function(previous, current, idx){
    return previous + ' ' + current;
}, "Hi"); 
//phrase = "Hi hello world"

Grouping Results

var cities = [{name: 'NY'}, {name: 'NY'}, {name: 'LA'}]
    .reduce(function(accumulator, current, idx){
        if(!accumulator[current.name]){
            accumulator[current.name] = 1;
        }else{
            accumulator[current.name]++; 
        }
        return accumulator;
    }, {});
//cities = {"NY":2,"LA":1}

Get Unique Values From a Collection

var uniques = [{name: 'NY'}, {name: 'NY'}, {name: 'LA'}]
    .reduce(function(collection, current, idx){
        if(collection.indexOf(current.name) < 0){
            collection.push(current.name)
        }
        return collection;
    }, []);
//uniques = ["NY","LA"]

Get Dupes with Closure

var dupes = [];
var states = [{name: 'NY'}, {name: 'NY'}, {name: 'CA'}]
    .reduce(function(accumulator, current, idx){
        if(accumulator.indexOf(current.name) >= 0){
            dupes.push(current.name); 
        }else{
            accumulator.push(current.name);
        }
        return accumulator;
    }, []);
//dupes = ["NY"]