Im wondering how to search big arrays using JavaScript.
Let's say we have an array consisting of elements that represent businesses. There are a couple thousand elements in the array, they are objects that sometimes also have arrays in them.
In each of those elements is a key eg called category that looks like this category: ["attr1", "attr2", "attr3"]
. Now I only want to find elements of the array that have a category like this:
category: ["Restaurant"]
The problem is that other keys of the elements in the array sometimes also have a property where "Restaurant" is in the name followed by something else eg "RestaurantPrice" so
if(array[i].categories != null &&
array[i].categories.indexOf("Restaurant") != -1) {
do something
}
Would not work properly because it would return all occurences of the word "Restaurant" or am I wrong?
If not how should I search for specific things in an array?
If categories
is an array like ["foobar", "foo"]
categories.indexOf("foo")
would return 1
, foobar would be ignored.
The other question was how to find elements efficient?
.
It depends, if your set is static, you can prebuilt and cache some sort of index like:
var categoriesMap = {
foobar: [1, 2, 4],
foo: [1, 5, 7]
}
The array would represent the indexes of items, which includes the given categories.
如果您的键是唯一的,请尝试使用HashMaps。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.