-2

I would to know how to simplify theses function calls by chaining them. Is there a way to chain forEach, push, destructuring array and map.

 let selectorsForLoader = ['a', 'b'];
 let loadingElements = [];
    selectorsForLoader.forEach(selector => {
      loadingElements.push(...Array.from(document.querySelectorAll(selector)));
    });
    let loaders = loadingElements.map(loadingElement => {
      loadingElement.doSomething();
    });

Here is an example of what I mean by function chaining:

   food.map(item => item.type)
  .reduce((result, fruit) => {
    result.push(fruit);
    return [...new Set(result)];
  }, []);
Dotista
  • 404
  • 3
  • 12

1 Answers1

-1

There you go:

['a', 'b'].flatMap(selector => {
    return Array.from(document.querySelectorAll(selector)));
  }).forEach(loadingElement => {
    loadingElement.doSomething();
  });

By the way, that "example" you gave should be written like this:

new Set(food.map(item => item.type));
David
  • 3,552
  • 1
  • 13
  • 24