35

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"];

6 Answers 6

53

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)
Sign up to request clarification or add additional context in comments.

Comments

21

Use Array.prototype.map():

const newArr = arr.map(i => 'images/' + i)

Same thing but without using ES6 syntax:

var arr = arr.map(function (i){
    return 'images/' + i;
})

Comments

6

For browser compatibility and without loop:

var pre = 'images/';
var arr = ['1.jpg', '2.jpg', 'some.jpg'];
var newArr = (pre + arr.join(';' + pre)).split(';');

1 Comment

What if the contents of the file name contains ";", as in "me;mycat.jpg"
2

You can simply do this with a simple loop:

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

for(var i = 0; i<arr.length; i++){
    newArr[i] = 'images/' + arr[i];
}

Comments

0

You can use Jquery library

var newArr = jQuery.map( arr, function( n, i ) {
  return ( "images/"+n );
});

4 Comments

Who said anything about jQuery?
I love how the jQuery version is longer than the native version - and slower
Native version is not work in IE 8. The question can be opened from the different parties, native approach has been proposed in other answers.
There are other substitutes for Array.map() that don't involve including an entire library. Johnroe Paulo Cañamaque's answer for example.
0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.