属性在对象数组中重复

时间:2017-04-12 01:21:39

标签: javascript

所以我正在处理以下具有两个属性名称和类型

的对象数组
  var pole = [
   {
       name: "Mike",
       type: "Pency",
   },
   {
       name: "Lesssy",
       type: "Pike",

   },
   {
       name: "Orcha",
       type: "Roo",
   },
   {
       name: "Roosvelt",
       type: "Zean",

   },
   {
       name: "Orange",
       type: "Pike",
   },
   {
       name: "Searie",
       type: "Zean",

   } ....... 100 Times

可以使用哪种Javascript方法来计算前3个最常见的名称'和出现次数

2 个答案:

答案 0 :(得分:1)

这似乎是一个大学/学校的问题,因此我不想给你完整的答案,但考虑这些步骤是为了一个简单(低效)的算法:

1) Keep track of all the names that you have found in the list

2) Include a counter for each of the names in terms of how often they pop up.

3) Loop through the array

4) counter++ each time its respective name pops up

5) Sort the list depending on the counter's count

6) return the top 3 (or 10, your question was unclear how many you wanted)

答案 1 :(得分:0)

您可以使用类似

的内容
function topN(obj, prop, n) {
  var groups = obj.reduce(function (res, i) {
    res[i[prop]] = (res[i[prop]] || 0) + 1;
    return res;
  }, {});

  var sortable = Object.keys(groups).reduce(function (res, i) {
    res.push({name: i, value: groups[i]});
    return res;
  }, []);

  sortable.sort(function (a, b) {
    return b.value - a.value;
  });

  var result = sortable.filter(function (item, index) {
    return index < n;
  }).map(function (i) {
    return i.name;
  });

  console.log(result);
}

topN(pole, 'name', 10);
topN(pole, 'type', 10);