javascript - 如何使用 Typescript/JS 查找数组中对象值出现的前 n 次?

标签 javascript arrays typescript find-occurrences

使用 TypeScript 我有一个对象数组,其中可能包含与数组中其他对象相同的值。例如,以下数组包含具有值“intent”的对象。我希望找到前 3 个最常发生的意图:

[
  {
    "intent": "hello",
    "other_value": "blah"
  },
  {
    "intent": "hello",
    "other_value": "blahblah"
  },
  {
    "intent": "hi",
    "other_value": "anothervalue"
  },
  {
    "intent": "hello",
    "other_value": "what?"
  },
  {
    "intent": "hello",
    "other_value": "eh?"
  },
  {
    "intent": "hi",
    "other_value": "okthen"
  },
  {
    "intent": "yo",
    "other_value": "alright"
  },
  {
    "intent": "hi",
    "other_value": "yes"
  },
  {
    "intent": "yo",
    "other_value":"yawhat?"
  },
  {
    "intent": "hey",
    "other_value": "meh"
  }
]

我正在尝试获得某种可以轻松显示前 3 个结果的结果,可能是键/值对数组或其他内容:

[
  {
    "intent": "hello",
    "occurrences": 4
  },
  {
    "intent": "hi",
    "occurrences": 3
  },
  {
    "intent": "yo",
    "occurrences": 2
  }
]

以下是我尝试的解决方案:

function top3(array) {
    let results = [];
    array.forEach(item => {
        if (results[item.intent] != null) {
          results[item.intent] += 1
        } else {
          results[item.intent] = 1;
        }
    });

    results = results.sort();
    return results.slice(0, 3);
}

但是,这仅返回出现值的数组,而不是意图本身的名称。所以我很难用数组找到哪个值属于哪个意图。

我尝试按照此解决方案中发布的答案进行操作:

Get the element with the highest occurrence in an array

但是,我不知道如何查找 n 次出现,而只是查找最上面的出现。我不确定如何使用该逻辑继续查找接下来的几次出现。

最佳答案

您可以首先通过构建一个对象数组来获取具有计数的对象,然后按出现次数对其进行降序排序,然后对数组进行切片以仅获取前三个元素。

var data = [{ intent: "hello", other_value: "blah" }, { intent: "hello", other_value: "blahblah" }, { intent: "hi", other_value: "anothervalue" }, { intent: "hello", other_value: "what?" }, { intent: "hello", other_value: "eh?" }, { intent: "hi", other_value: "okthen" }, { intent: "yo", other_value: "alright" }, { intent: "hi", other_value: "yes" }, { intent: "yo", other_value: "yawhat?" }, { intent: "hey", other_value: "meh" }],
    count = data
        .reduce((r, { intent }) => {
            r[intent] = r[intent] || { intent, occurences: 0 };
            r[intent].occurences++;
            return r;
        }, {}),
    top3 = Object
        .values(count)
        .sort((a, b) => b.occurences - a.occurences)
        .slice(0, 3);
    
console.log(top3);
console.log(count);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何使用 Typescript/JS 查找数组中对象值出现的前 n 次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50045690/

相关文章:

javascript - 如何将API Gateway SDK添加到React中?

ruby:数组中所有元素的索引小于给定值

TypeScript,将多个参数绑定(bind)到同一类型

javascript - 当没有内容以 Angular 6 显示时如何停止滚动?

javascript - 阿尔法任何地方 : How to get all the data from the list so that I can access them using Javascript

c++ - 堆上非常大的数组 (Visual C++)

javascript - 这不会访问 http 响应对象 :property does not exist on type Object

typescript - 如何将元组类型转换为联合?

javascript - bValidator 函数返回 true 时如何调用函数?

java - 用曼哈顿距离模式填充二维数组