我有两个名为active_filters
和cars
的数组。我正致力于提高性能,并且我发现下面的代码非常重且速度慢。我想知道是否有可能在没有外部forEach的情况下比较汽车数组中的x.value和element [0]?我对此非常陌生,所以感谢任何帮助!如果有更好的解决方法,我可以接受建议:)谢谢!!!
cars.forEach(function(element) {
active_filters.find(x => x.value === element[0].getAttribute("data-location-id"));
});
更新
我的目标是返回属性data-location-id(位于cars数组中)是否位于active_filters数组中的value属性。
示例数据:
有效过滤器数组对象
{class: "data-location-id", value: "AD-48.7284-2.3601"}
{class: "data-location-id", value: "AL-48.726243-2.365247"}
汽车阵列:
<li data-location-id="ZT-48.8308-2.3567" class="listing"></li>
<li data-location-id="AD-48.7284-2.3601" class="listing"></li>
<li data-location-id="AC-28.7284-2.3601" class="listing"></li>
答案 0 :(得分:2)
要获取每个元素的结果,请使用map()
,而不是forEach()
。它们都遍历数组并调用函数,但forEach()
会丢弃结果,而map()
会将所有结果收集到数组中。
cars.map(car => !!active_filters.find(x => x.value === car.data("location-id")));
!!
将find()
的结果转换为布尔值true/false
。
答案 1 :(得分:0)
要将时间复杂度降低到线性,您可以使用&#34; data-location-id&#34;创建一个对象。作为active_filters数组的键。这将使您能够进行恒定时间查找,只使用单个循环而不是嵌套循环。
const active_filters = [
{ class: "data-location-id", value: "AD-48.7284-2.3601" },
{ class: "data-location-id", value: "AL-48.726243-2.365247" }
];
// from active filters, create this active_filtersById object
// with the value as keys for constant time lookup
const active_filtersById = {
"AD-48.7284-2.3601": { class: "data-location-id", value: "AD-48.7284-2.3601" },
"AL-48.726243-2.365247": { class: "data-location-id", value: "AL-48.726243-2.365247" }
}
const cars = [
{ "data-location-id": "ZT-48.8308-2.3567" },
{ "data-location-id": "AD-48.7284-2.3601" },
{ "data-location-id": "AC-28.7284-2.3601" }
];
const result = cars.map(car => {
const id = car["data-location-id"];
const isFound = active_filtersById[id];
return isFound !== undefined;
})
console.log(result)
// result is [false, true, false]
&#13;