Javascript shortcut, to append string into all the values of array?

I have an array = ["a", "b", "c"];

What I want is i have an string let us say "Hello", that I want to append to each and every value of this array.

My expected output is something like

["Hello_a", "Hello_b", "Hello_c"]

Is there any shortcut in javascript to perform this operation, without using any loop .

Any help is appreciated !

Thanks

Answers:

Answer

Try to use Array.prototype.map() at this context,

var yourArray = ["a", "b", "c"];
var transformed = yourArray.map(function(item){
  return "Hello_" + item;
});
console.log(transformed); // ["Hello_a", "Hello_b", "Hello_c"]

Also you can use fat Arrow functions if users of you are updated with latest browsers.

var yourArray = ["a", "b", "c"];
var transformed = yourArray.map(item => "Hello_" + item);
console.log(transformed); // ["Hello_a", "Hello_b", "Hello_c"]

As a side note, you have to sure about arrow functions that it will forcibly use lexical this inside of it.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.