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"];
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.
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().
The + prefix converts the value into a number.
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.
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.
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.
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.
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)
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; })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With