Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add prefix to array values?

Tags:

javascript

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"]; 
like image 310
Navin Rauniyar Avatar asked Sep 30 '14 08:09

Navin Rauniyar


People also ask

What is prefix in an array?

Prefix array is a very vital tool in competitive programming. This helps to minimize the repeated calculation done in an array and thus reduces the time complexity of your program.

How do you add an element to an array array?

When you want to add an element to the end of your array, use push(). If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().

What is prefix in Javascript?

The + prefix converts the value into a number.

How do you add a prefix to an array in JavaScript?

While accessing the array, update the element by adding the prefix with all the elements. Create an array with elements. strArray is a collection. Str is a variable name. Create a for loop. To go to the next element by incrementing. It will add a prefix to the existing elements in an array.

How to add prefix on each key of array without loop?

But we can do this without using any kind of loop. using array_combine (), array_keys () and array_map () through we can add prefix on each key of array, In Bellow example you can see how to use both function together and add faster way to add prefix of every item key: I'm a full-stack developer, entrepreneur and owner of Aatman Infotech.

How do I add prefixes and suffixes in word?

In the Add Text dialog box, enter your prefix or suffix in the Text box, check the Before first character option (for adding prefix) or After last character option (for adding suffix) as you need, and click the Ok button.

How to add prefix or suffix to selected range of cells?

However, work goes hard and time-consuming when there are numerous cells. This article will show you some tips about adding prefix or suffix to selected range of cells in Excel easily. The Excel's concatenate function can insert prefix or suffix for a single cell quickly. 1.


2 Answers

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) 
like image 126
Roman Kolpak Avatar answered Sep 30 '22 17:09

Roman Kolpak


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; }) 
like image 23
Todd Mark Avatar answered Sep 30 '22 17:09

Todd Mark