代码之家  ›  专栏  ›  技术社区  ›  Sumchans

类型脚本在数组中计数重复项并按每个项的计数对结果进行排序

  •  0
  • Sumchans  · 技术社区  · 7 年前

    我有一个数组,它是根据从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 回复  |  直到 7 年前
        1
  •  1
  •   Ele    7 年前

    另一种方法是使用函数 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; }
        2
  •  1
  •   Get Off My Lawn    7 年前

    首先要做的是得到一个唯一的项目列表,然后循环该列表以添加到最终结果中。

    生成列表后,我们可以使用键对列表进行排序 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);