How can I simplify this JavaScript code by chaining functions?
P粉099145710
P粉099145710 2023-07-28 22:21:25
0
1
582
<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粉099145710
P粉099145710

reply all(1)
P粉019353247

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));
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template