Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading