i have array contains mix of objects , strings. need transform array object array.
the input array:
[ {"text": "address"}, {"text": "newtag"}, {"text": "tag"}, "address", "name", "profile", {"text": "name"}, ] the out array should this:
[ {"tag": "address", count: 2}, {"tag": "name", count: 2}, {"tag": "newtag", count: 1}, {"tag": "profile", count: 1}, {"tag": "tag", count: 1}, ] here code (it looks stupid):
var tags = [], tansformedtags=[]; (var = 0; < input.length; i++) { if (_.isobject(input[i])) { tags.push(input[i]['text']); } else { tags.push(input[i]); } } tags = _.countby(tags, _.identity); (var property in tags) { if (!tags.hasownproperty(property)) { continue; } tansformedtags.push({ "tag": property, "count": tags[property] }); } return _.sortbyorder(tansformedtags, 'tag'); i want know if there better , more elegant way perform operation?
_(arr) .map(function(item) { return _.get(item, 'text', item); }) .countby() .map(function(value, key) { return { text: key, count: value }; }) .value();
Comments
Post a Comment