0

ok I have the following:

var arr1 = ['value1','value2'];
var name = 'name';
var joinarray = arr1.join('|');

which gives me:

'value1|value2'

but i need:

value1 name|value2 name

how do i go about adding the variable in at the end of each array value?

1
  • Maybe: arr1.map(function (value) { return value + " " + name; }).join("|"); Commented May 13, 2014 at 21:12

2 Answers 2

3

Try this:

var joinarray = arr1.join(name + '|') + name;

It's a bit hackish. Another alternative would be to loop over the array and add name to each array item, and then do the arr1.join call at the end.

for (var i = 0; i < arr1.length; i++) {
    arr1[i] = arr1[i] + " " + name;
}
var joinarray = arr1.join('|');

Map is another good alternative, especially if you want to keep the code to one line.

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

Comments

2

Add it to each array value by using map before joining:

var joined = arr1.map(function(val){ return val+' '+name; }).join('|');

1 Comment

this seemed more elegant!

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.