with reduce
HTML
<script>
var _consoleLog = console.log;
console.log = function(){
var name = _consoleLog.apply(console,arguments);
var str = "";
for(var index in arguments){
if(Array.isArray(arguments[index])){
arguments[index] = arguments[index].map(function(item){
if(typeof item == "object"){
item = JSON.stringify(item,null,4)+"<br>";
}
return item;
});
str += arguments[index]+" ";
} else if(typeof arguments[index] == "object"){
str += JSON.stringify(arguments[index],null,4);
} else {
str += arguments[index]+" ";
}
}
$('body').append("<div>"+str+"</div>");
}
</script>
TypeScript
var arr = ["apple","","apple","pear"];
function getWordCnt(){
return arr.reduce(function(prev,next,index){
console.log("<b>Iteration "+index+"</b>");
console.log("prev:",prev);
console.log("next:",next);
prev[next] = ++prev[next] || 1;
console.log("Passing this to the 'prev' of the next iteration if any:",prev);
console.log("---------------");
return prev;
},{});
}
console.log("<b>Final Object:</b>",getWordCnt());