0

I have an array of Objects in JavaScript and I'm having trouble accessing JS methods on my array.

Is there a way to use methods such as removeClass or attr on an array without having to use a for loop? For example, in jQuery if I do $("li.listing").removeClass("listing")....it will remove the listing class from all li tags where this class is present.

Is there a way without having to use multiple for loops, to use these methods on an array (so that it looks at each element/object in the array)?

Example

cars.removeClass("listing") // Remove listing class from every element in cars array - is this syntax or something similar possible? Thanks!

Array index [0] example

0: m.fn.init [
  li#listing-MCMR-R-ZT-BFNT001-ZT-BFNT001.listing.filtered-out-by-car-type.listing-filtered-out, 
  prevObject: m.fn.init(1), 
  context: car, 
  selector: "li.listing"
]
Pabs123
  • 3,385
  • 13
  • 29
Michael
  • 403
  • 1
  • 9
  • 28

1 Answers1

2

You can use Array.prototype.map to simplify the syntax a bit, but it is essentially also going to loop through all the elements. Under the hood, jQuery is also looping through them, all it is doing is giving you a nice way to access that without having to write the loop yourself

for your example:

cars.map(function(car) { 
   return car.removeClass('listing');
});

As pointed out in the comments, Array.prototype.forEach Is probably preferable if you're only looking to mutate or apply the function on the current array and not return anything new. In either case, this is the most succinct way of going through an array without using an explicit for loop

Pabs123
  • 3,385
  • 13
  • 29
  • 1
    I'm not sure, but wouldn't .forEach be preferable over .map if you're not returning the array? – Cody G Apr 18 '18 at 18:14
  • depends on the desired result for sure! I suppose in this specific case forEarch could be preferable. Either way, one of the two methods is the correct way to go – Pabs123 Apr 18 '18 at 18:18
  • Do you know if there is a performance difference between .forEach and an actual for loop? – Michael Apr 18 '18 at 18:23
  • theoretically forEach is a bit slower due to the overhead of calling a function on every single loop (good explanation here https://stackoverflow.com/a/43821929/1148244), but practically speaking the difference should be insignificant. forEach provides good readability and prevents you from dealing with extra variables, though you should be good to use either one – Pabs123 Apr 18 '18 at 18:27
  • no problem! be sure to accept the answer if it solved your problem so future readers can benefit :) – Pabs123 Apr 18 '18 at 18:30
  • @Pabs123 Similar question. If I wanted to achieve the length of elements in car array with `filtered-out` class... do you know the best way for me to achieve this? Ex...similar to $('li.listing-filtered-out').length but using `cars` array – Michael Apr 18 '18 at 19:26