繁体   English   中英

使用underscore.js合并数组

[英]Merge arrays with underscore.js

在执行了一些underscore.js操作( _.map_.each . _.map_.each . _.pluck_.flatten )之后,我得到了一个对象数组,如下所示:

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做些事情?

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

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

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"
}]

联合会

我只用两个_.each

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;
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM