javascript - Lodash get repetition count with the object itself -
i have array of objects like:
[ { "username": "user1", "profile_picture": "testjpg", "id": "123123", "full_name": "user 1" }, { "username": "user2", "profile_picture": "testjpg", "id": "43679144425", "full_name": "user 2" }, { "username": "user2", "profile_picture": "testjpg", "id": "43679144425", "full_name": "user 2" } ]
i want get:
[ { "username": "user1", "profile_picture": "testjpg", "id": "123123", "full_name": "user 1", "count": 1 }, { "username": "user2", "profile_picture": "testjpg", "id": "43679144425", "full_name": "user 2", "count": 2 } ]
i've used lodash a.k.a. underscore method failed process it.
var uniquecomments = _.chain(comments).uniq(function(item) { return item.from.id; }).value(); var rescomment = []; _.foreach(uniquecomments, function(unco) { unco.count = _.find(comments, function(comment) { return unco.id === comment.id }).length; rescomment.push(unco); });
the result should in rescomment
.
edit: updated array of objects.
i'd using _.reduce()
, since that's you're doing--reducing given array (potentially) smaller array containing different sort of object.
using _.reduce()
, you'd this:
var rescomment = _.reduce(comments, function(mem, next) { var username = next.username; var existingobj = _.find(mem, function(item) { return item.username === username; }); existingobj ? existingobj.count++ : mem.push(_.extend(next, {count: 1})); return mem; }, []);
and here jsfiddle.
Comments
Post a Comment