使用underscore.js合并数组

时间:2015-09-30 23:51:49

标签: javascript arrays underscore.js

执行一些underscore.js操作(_.map_.each_.pluck_.flatten)后,我有一个对象数组,如下所示:< / p>

var userArray = [
  {id: 123456, username: "bill123", group: "ONE"},
  {id: 123457, username: "joe123", group: "TWO"},
  {id: 123457, username: "joe123", group: "TWO"},
  {id: 123458, username: "jim123", group: "ONE"}
]

我需要创建一个新数组,删除重复项,并计算对象在数组中出现的次数。我能够通过两个单独的underscore.js函数获得所需的结果,但是在合并这两个结果时遇到了问题。

工作职能如下:

var uniqUsers = _.uniq(taggedUsers, false, function(user) {
  return user.id
});
  //returns array of unique objects in the same format as above
  //[{id: 123457, username: "joe123", group: "TWO"},...]

var userCounts = _.countBy(taggedUsers, "id");
  //returns the count for each user in the userArray in a single object
  //{123456: 1, 123457: 2, 123458: 1}


返回像这样的对象数组的最佳方法是什么:

{id: 123457, username: "joe123", group: "TWO", count: 2}

我可以在_.countBy功能中添加其他字段吗?或者我需要对_.map做些什么吗?

任何帮助将不胜感激!感谢

2 个答案:

答案 0 :(得分:4)

您可以在map上使用userCounts创建一个新阵列,然后对其进行排序。

var userArray = [
  {id: 123456, username: "bill123", group: "ONE"},
  {id: 123457, username: "joe123", group: "TWO"},
  {id: 123457, username: "joe123", group: "TWO"},
  {id: 123458, username: "jim123", group: "ONE"}
];

var userCounts = _.countBy(userArray, "id");

var result = _.sortBy(_.map(userCounts, function(count, id) {
  var user = _.findWhere(userArray, {id: Number(id)});  
  return _.extend({}, user, {count: count});
}), 'count');

console.log(result);

结果:

[[object Object] {
  count: 1,
  group: "ONE",
  id: 123456,
  username: "bill123"
}, [object Object] {
  count: 1,
  group: "ONE",
  id: 123458,
  username: "jim123"
}, [object Object] {
  count: 2,
  group: "TWO",
  id: 123457,
  username: "joe123"
}]

JSBin

答案 1 :(得分:3)

我会在两个_.each s中执行此操作:

var uniquedUsersWithCount = [],
    userIDToCount = {};

_.each(taggedUsers, function (user) {
  if (userIDToCount[user.id] !== undefined) {
    userIDToCount[user.id] += 1;
  } else {
    userIDToCount[user.id] = 0;
    uniquedUsersWithCount.push(user);
  }
});

_.each(uniquedUsersWithCount, function (user) {
  var count = userIDToCount[user.id];
  if (count !== undefined) {
    user.count = count;
  }
});