javascriptarrayssimplifymethod-chainingsimplification

How to simplify this code in Javascript via function chaining?


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)];
  }, []);

Solution

  • 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));