gpt4 book ai didi

javascript - 更快地找到具有频率值的二维关键字数组的出现

转载 作者:搜寻专家 更新时间:2023-11-01 04:49:44 25 4
gpt4 key购买 nike

我是否有更快的方法来计算二维数组中所有元素的所有频率?喜欢这个示例:

var array = [["a", "b"]["c", "d"]["b", "d"]["c", "a", "b"], ["a", "b", "c", "d"];

我的预期结果是包含关键字和频率值的对象数组。
像这样,

result = [{ keyword: "a",
frequency: 3
}, {
keyword: "b",
frequency: 4
}, ... ];

这是我的解决方案:

function generateData (records) {
var data = [];
for (var i = 0; i < records; ++i) {
data.push(["a", "b", "c", "d", "e"]);
}
// some gap to insert data
setTimeout(function () {
}, Math.random() * 1000);
return data;
}

function mine (data) {
var result = [];
data.forEach( function (keywords) {
for (var i = 0, len = keywords.length; i < len; ++i) {
var pos = result.map( function (x) {
return x.keyword;
}).indexOf(keywords[i]);

if (pos == -1) {
var newKeyword = {
keyword: keywords[i],
frequency: 1
}
result.push(newKeyword);
} else {
result[pos].frequency += 1;
}
}
});
return result;
}

var dataset = generateData(50000);

var start = performance.now();
var result = mine(dataset);
var end = performance.now();

console.log(result);
console.log("Total time: " + (end - start) + " milliseconds.");

有没有人有更快的方法来解决这个问题?注意:使用二维关键字数组(约 50,000 条记录)。

最佳答案

您可以使用 .reduce() 以对象的形式获取所需的频率:

let data = [
["a", "b"],
["c", "d"],
["b", "d"],
["c", "a", "b"],
["a", "b", "c", "d"]
];

let result = [].concat(...data).reduce((r, c) => (r[c] = (r[c] || 0) + 1, r), {});

console.log(result);

关于javascript - 更快地找到具有频率值的二维关键字数组的出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54248476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com