Skip to content

Instantly share code, notes, and snippets.

@pmiguel
Created April 30, 2015 13:29
Show Gist options
  • Save pmiguel/4fb9579abbd60bd0c994 to your computer and use it in GitHub Desktop.
Save pmiguel/4fb9579abbd60bd0c994 to your computer and use it in GitHub Desktop.
var phrase = "I love to be me. I think me is awesome. Is is a good call. love awesome.";
function mapReduce(string) {
var reduced = [];
var replaced = string.replace(/\./g, '');
var tokens = replaced.split(' ');
var mappedStr = tokens.map( function(element) {
return {s:element, n:1};
});
var sorted = mappedStr.sort(function(a,b) {
if(a.s < b.s) return -1;
if(a.s > b.s) return 1;
return 0
})
var reduce1 = sorted.reduce( function(a, b, i, array) {
if(a.s === b.s) {
return {s: a.s, n: a.n + b.n};
} else {
reduced.push(a);
}
return b;
});
reduced.push(reduce1);
return reduced;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment