lodash - How to count same items with specail form in a array (javascript) -
for example:
input: var arr = ['a','b','c','a-5','c-2']; output: var result = {'a':6,'b':1,'c':'3'} ;
my solution is:
function countsameitem(arr) { var counter = {}; (var = 0; < arr.length; i++) { var item = arr[i].split('-'); if (item.length === 1) { counter[item] = (counter[item] + 1) || 1; } else { counter[item[0]] = (counter[item[0]] + parseint(item[1]) || parseint(item[1])); } } return counter; }
but want thought more consise solution using lodash
you can concisely without lodash:
var result = ['a','b','c','a-5','c-2'].reduce(function(o, s) { var = s.split('-').concat(1); return o[a[0]] = (o[a[0]] || 0) + +a[1], o; }, object.create(null));
Comments
Post a Comment