Reputation:
I have a big object (called "container" in the following code) from a json file. This object contains many elements (about 20 000), each of it being an object with a "rank" property. It is too big to print it here, but here is an object with a same structure:
{
guy1: {rank:0, infos:"the first guy ever"},
guy0: {rank:2, infos:"another guy"},
something: {rank:1, infos:"something else"}
}
First I wanted to put the 10 of them with the smallest rank in a list (after I slightly modified them with a function I call here modify), so I did:
var res = [];
for (var key in container) {
if (container.hasOwnProperty(key) && container[key]["rank"]<10) {
res.push(modify(container[key]));
}
}
But now I want to do_something with the 10 of them with the smallest rank but only among those who pass my_test. I could do:
var res = [];
var filt_cont = Array.from(container).filter(my_test);//actually this doesn't work. I currently use a long non-efficient way to do that but i guess I can find something better on my own)
for (var key in filt_cont) {
if (filt_cont.hasOwnProperty(key) && filt_cont[key]["rank"]<10) {
res.push(modify(filt_cont[key]));
}
}
but as I want my code to be the fastest possible I would like to know if there is a faster way to do that. Also I want to keep the 10 best (with the smallest rank) among those who pass the test, and this only gives those who both were in the first 10 before the filter and pass the filter.
It that's relevant, my_test is four comparisons and two attributes readings and modify is 6 attribute readings and 2 int additions.
Upvotes: 2
Views: 233
Reputation:
Finally I go with this:
var filt_cont = []
for (var key in container) {
filt_cont[container[key]["rank"]] = container[key]
}
filt_cont = filt_cont.filter(my_test)
return filt_cont[0:9]
Works fast enough, apparently creating a list like this, adding items by their index, is not too expensive.
I note that if undefined would pass my_test that could be a problem, but as that's not the case it's alright.
Upvotes: 1