[英]What is the best way to process large arrays in Javascript?
I have a React JS app that uses an API to pull a JSON object that contains an array of 10,000+ objects.我有一个 React JS 应用程序,它使用 API 来拉取 JSON object,其中包含 10,000 多个对象的数组。 This array is then used to populate a table, with certain filters and options from checkboxes, dropdowns, that can manipulate the data.
然后,该数组用于填充表格,其中包含某些过滤器和复选框、下拉列表中的选项,可以操纵数据。 When tapping a checkbox, filter, sort, reduce functions are used on the array to return a specific subset of the array that can populate the table again.
当点击复选框时,在数组上使用过滤器、排序和归约函数来返回可以再次填充表的数组的特定子集。
There are 10-15 options to choose from, so 10-15 filter/map/reduce functions running on the data each time a box is checked.有 10-15 个选项可供选择,因此每次选中一个框时都会对数据运行 10-15 个过滤器/映射/减少函数。
These filtering options now cause a noticeable lag between clicking on the checkbox and changing the table.这些过滤选项现在会在单击复选框和更改表格之间造成明显的延迟。 The app freezes while it calculates the new array.
应用程序在计算新数组时冻结。 Is there a more efficient flow to filter my data?
是否有更有效的流程来过滤我的数据?
Some example functions below below:下面的一些示例函数:
//gameData is an array of 10k+ objects
let inData = gameData
const options = {
dateToTime: new Date('2020-03-01'),
servers:[1,2,3],
maps:['A','B','C']
}
function groupByArray(array, key) {
return array.reduce(function (rv, x) {
let v = key instanceof Function ? key(x) : x[key];
let el = rv.find((r) => r && r.key === v);
if (el) {
el.values.push(x);
} else {
rv.push({ key: v, values: [x] });
} return rv;
}, []);
}
const gamesGrouped = groupByArray(inData, 'gameid')
inData = gamesGrouped.filter(a => a.playername != "new")
inData = inData.filter(game => {
const thisTime = new Date(game.creationtime)
return (thisTime < options.dateToTime)
})
inData = inData.filter(game => options.servers.includes(game.serverip))
inData.filter(game => options.maps.includes(game.map))
Thanks in advance!提前致谢!
I would say it is impossible to give general answer how to process array data, but I can give some pointers.我想说不可能给出如何处理数组数据的一般答案,但我可以给出一些指示。
Also code that you provided is bit cryptic, you might want to use better naming.您提供的代码也有点神秘,您可能希望使用更好的命名。
Here is performance comparison for groupByArray() function: https://jsbench.me/t7kltjm1sy/1这是 groupByArray() function 的性能比较: https://jsbench.me/t7kltjm1sy/1
Worth noting, whenever I deal with performance sensitive situations I keep code to the VanillaJS as close as possible, because with large data sets even slight function overhead can be noticeable.值得注意的是,每当我处理对性能敏感的情况时,我都会尽可能地将代码与 VanillaJS 保持一致,因为对于大型数据集,即使是轻微的 function 开销也会很明显。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.