0

With an array, how would I append a character to each element in the array? I want to add the string ":" after each element and then print the result.

 var a = [54375, 54376, 54377, 54378, 54379, 54380, 54381, 54382, 54383, 54384, 54385, 54386, 54387, 54388, 54389, 54390, 54391, 54392, 54393, 54394, 54395, 54396, 54397, 54400, 54402, 54403, 54405, 54407, 54408];

For example: 54375:54376:54377

1
  • your question is ambiguous, do you want a concatenated string with all the numbers separated by colon (as in your example) or an array a = [ "54375:", "54376:", "54377:", "54378:" ...] Commented Jan 16, 2014 at 20:46

2 Answers 2

5
a = a.map(function(el) { return el + ':'; });

Or if you want to join them into a string:

var joined = a.join(':');
Sign up to request clarification or add additional context in comments.

2 Comments

I think the join() approach is what OP is after here.
return a + ':'??!?!
2

If you are looking for a way to concatenate all the elements with :, you can use this

var result = "";
for (var i = 0; i < a.length; i += 1) {
    result += a[i] + ":";
}
result = result.substr(0, result.length-1);

Or even simpler, you can do

a = a.join(":");

If you are looking for a way to append : to every element, you can use Array.prototype.map, like this

a = a.map(function (currentItem) {
    return currentItem + ":";
});
console.log(a);

If your environment doesn't support map yet, then you can do this

for (var i = 0; i < a.length; i += 1) {
    a[i] = a[i] + ":";
}

3 Comments

@VisioN Indeed. But I was just listing down the various ways to do this and reduce was the first one to come to my mind.
Well, there are many other extreme ways, e.g. ([123,345,456,567]+[':']).replace(/,/g, ':');.
@VisioN I understand the sarcasm, but it should have been [''] or '' as per the OP's requirement and I removed the reduce version :)

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.