Home  >  Q&A  >  body text

How can I simplify this JavaScript code by chaining functions?

<p>I would like to know how to simplify these function calls by chaining them. Is there a way to chain forEach, push, destructuring arrays and map together. </p> <pre class="brush:php;toolbar:false;">let selectorsForLoader = ['a', 'b']; let loadingElements = []; selectorsForLoader.forEach(selector => { loadingElements.push(...Array.from(document.querySelectorAll(selector))); }); let loaders = loadingElements.map(loadingElement => { loadingElement.doSomething(); });</pre> <p>Here is an example: </p> <pre class="brush:php;toolbar:false;">food.map(item => item.type) .reduce((result, fruit) => { result.push(fruit); return [...new Set(result)]; }, []);</pre> <p><br /></p>
P粉099145710P粉099145710449 days ago544

reply all(1)I'll reply

  • P粉019353247

    P粉0193532472023-07-29 18:29:37

    What about this

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

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

    new Set(food.map(item => item.type));

    reply
    0
  • Cancelreply