Michael
Michael

Reputation: 443

Using Find & ForEach in JS Together

I have two arrays called active_filters and cars. I'm working on improving performance and I'm finding that the code below is super heavy and slow. I'm wondering if it's possible to compare x.value and element[0] from cars array without having the outer forEach? I'm super new to this, so appreciate any help! If there's a better way of going about this too, I'm open to suggestions :) Thanks!!!

 cars.forEach(function(element) {
    active_filters.find(x => x.value === element[0].getAttribute("data-location-id"));
 });

Update:

My goal is to return whether or not the attribute data-location-id (which is located in the cars array) is located and equal to the value property in the active_filters array.

Sample Data:

Active Filters Array Object

{class: "data-location-id", value: "AD-48.7284-2.3601"}
{class: "data-location-id", value: "AL-48.726243-2.365247"}

Cars Array:

<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>

Upvotes: 0

Views: 12534

Answers (2)

wiziwig
wiziwig

Reputation: 26

To reduce your time complexity to linear, you can create an object with the "data-location-id" as the keys from the active_filters array. This will give you the ability to do a constant time lookup and just use a single loop instead of nested loops.

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]

Upvotes: 0

Barmar
Barmar

Reputation: 781088

To get a result for each element, you use map(), not forEach(). They both iterate over the array and call the function, but forEach() discards the result, while map() collects all the results into an array.

cars.map(car => !!active_filters.find(x => x.value === car.data("location-id")));

!! turns the result of find() into a boolean true/false.

Upvotes: 2

Related Questions