javascriptarrays

How to add prefix to array values?


I have an array of values to which I want to add some prefix:

var arr = ["1.jpg", "2.jpg", "some.jpg"];

Adding the prefix images/ should result in this:

newArr = ["images/1.jpg", "images/2.jpg", "images/some.jpg"];

Solution

  • Array.prototype.map is a great tool for this kind of things:

    arr.map(function(el) { 
      return 'images/' + el; 
    })
    

    In ES2015+:

    arr.map(el => 'images/' + el)