1

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

1
  • 2
    .map(x => 'Hello_' + x) - does it count as a loop? Commented Mar 7, 2016 at 11:53

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

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.