typescript计算数组中的重复项,并按每个项的计数对结果进行排序

时间:2018-06-03 01:54:01

标签: javascript arrays typescript

我有一个数组,根据从api调用中提取的值填充。 数组将具有这样的值

["9777", "9777", "2.4", "9777", "2.4", "2.4", "9777", "2.4", "2.4", "9777", "9777", "2.4", "2.4", "2.4"]

我要做的是获取数组中每个项目的出现次数,并根据计数对其进行降序排序。

我这样做是从stackoverflow得到的:

data.forEach(function (x) {
  counts[x] = (counts[x] || 0) + 1;
});

它可以工作,但它会产生奇怪的结果,这使得很难从结果中提取值。 结果如下: enter image description here

2 个答案:

答案 0 :(得分:1)

另一种方法是使用函数reduce来计算和创建带有计数的对象,然后使用函数sort

如果要通过" name"提取特定对象,可以使用函数find



let array = ["9777", "9777", "2.4", "9777", "2.4", "2.4", "9777", "2.4", "2.4", "9777", "9777", "2.4", "2.4", "2.4"],
    counts = Object.values(array.reduce((a, c) => {
      (a[c] || (a[c] = {name: c, count: 0})).count += 1;
      return a;
    }, {})).sort(({count: ac}, {count: bc}) => bc - ac),
    target = "2.4",
    found = counts.find(({name}) => name === target);

console.log(counts);
console.log(found);
console.log(found.count);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:1)

要做的第一件事就是获取一个唯一的项目列表,然后遍历该列表以添加到最终结果。

生成列表后,我们可以使用我们从上一个操作创建的密钥count对列表进行排序。

const items = ["9777", "9777", "2.4", "9777", "2.4", "2.4", "9777", "2.4", "2.4", "9777", "9777", "2.4", "2.4", "2.4"];

// A place to store the results
const result = [];

// Create a unique list of items to loop over
// Add each item to the result list
[...new Set(items)].forEach(item => result.push({
  key: item,
  // Get the count of items of the current type
  count: items.filter(i => i == item).length
}));

// Sort the array from highest to lowest
result.sort((a, b) => b.count - a.count);

console.log(result);