How can I simplify this JavaScript code by chaining functions?
P粉099145710
2023-07-28 22:21:25
<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>
What about this
By the way, the "example" you gave should be written like this: