Search code examples
javascripthtmlcollection

How do you convert document.images into an array of src string?


Using Array.filter seems to return the same array that I passed in.

How do you return an array of image src strings? And not array of image elements?

var collection = document.images;
var arr = [].slice.call(collection);
var filtered = arr.filter(function(x) { return x.src });

the variable filtered is an array of image elements and not image src string :/


Solution

  • Try map

    The map() method creates a new array with the results of calling a provided function on every element in this array.

    var collection = document.images;
    var arr = [].slice.call(collection);
    var srcArr = arr.map(function(x) { return x.src });
    

    The filter() method creates a new array with all elements that pass the test implemented by the provided function.

    In your case the filter function always return the url, we need an expression which return truthy or false value inside filter function.