2

Input: The Array of the strings

var arr = ['a','b','c'];
var prefix = 'prefix_';

Output: Each element in the array should be prefixed by 'prefix':

['prefix_a','prefix_b','prefix_c']
2
  • But, what have you tried? Commented Aug 10, 2018 at 10:12
  • 1
    Yes, I had tried and even added my own answer and accepted the more optimized and simple answer provided by void. I did search on stackoverflow and other sites for the solutions but couldn't find any. Even the stackoverflows question suggester was showing similar questions in some other languages but not in javascript. @zakaria-acharki, thank you for pointing to the original question, I've upvoted the question and answer. Commented Aug 10, 2018 at 11:26

2 Answers 2

5

You just need to use Array.prototype.map here, it transforms each element of the array based on the callback method.

var arr = ['a','b','c'];
var prefix = 'prefix_';

var newArr = arr.map(el => prefix + el);
console.log(newArr);

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

Comments

1

A simpler, ES6 way using Array#map :

const prefixArray = (array, prefix) => array.map(e => prefix+e);

Demo:

let arr = ['a','b','c'];
const prefix = 'prefix_';

const prefixArray = (array, prefix) => array.map(e => prefix+e);

console.log(prefixArray(arr,prefix));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.