Home > OS >  How to show in Array.map() html files only?
How to show in Array.map() html files only?

Time:06-03

I'm using this Array.map() to list files in cache:

<div data-offline></div>
    <script>
        if (navigator && navigator.serviceWorker) {
            caches.open('pages').then(function (cache) {
                cache.keys().then(function (keys) {
                    var offline = document.querySelector('[data-offline]');
                    offline.innerHTML =
                        '<ul>'  
                            keys.map(function(key) {
                                return '<li><a href="'   key.url   '">'   key.url   '</a></li>';
                            }).join('')  
                        '</ul>';
                });
            });
        }
    </script>

This is listing all kind of files in cache - html, js, css, images etc.

But I'd like to list html files only. There is a way to do it?

CodePudding user response:

Yes, there is a way: In addition to map, which transforms elements with the given function, you can use filter, which returns only those elements where the given function returns true.

So you would use keys.map(f).filter(g).join('')in your example, where f is your mapping function and g is your function that determines whether a file is of type html.

See https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/filter.

CodePudding user response:

Use Array.prototype.filter to exclude files before mapping them

Updated Example

"<ul>"  
keys
  .filter(function (key) {
    return !key.url.endsWith(".html");
  })
  .map(function (key) {
    return '<li><a href="'   key.url   '">'   key.url   "</a></li>";
  })
  .join("")  
"</ul>";
  • Related