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"];
const newArr = arr.map(i => 'images/' + i)
Same thing but without using ES6 syntax:
var arr = arr.map(function (i){
return 'images/' + i;
})
For browser compatibility and without loop:
var pre = 'images/';
var arr = ['1.jpg', '2.jpg', 'some.jpg'];
var newArr = (pre + arr.join(';' + pre)).split(';');
You can use Jquery library
var newArr = jQuery.map( arr, function( n, i ) {
return ( "images/"+n );
});
Array.map() that don't involve including an entire library. Johnroe Paulo Cañamaque's answer for example.You can use Rest parameters with Array.prototype.map().
function addPathPrefix(prefix, ...filenames) {
return filenames.map((filename) => `${prefix}${filename}`)
}
const arr = ["1.jpg", "2.jpg", "some.jpg"]
console.log(addPathPrefix("images/", ...arr))