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:" ...]
    – max
    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(':');
2
  • 1
    I think the join() approach is what OP is after here. Commented Jan 16, 2014 at 15:59
  • return a + ':'??!?! Commented Jan 16, 2014 at 16:00
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
  • @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. Commented Jan 16, 2014 at 16:06
  • Well, there are many other extreme ways, e.g. ([123,345,456,567]+[':']).replace(/,/g, ':');.
    – VisioN
    Commented Jan 16, 2014 at 16:07
  • @VisioN I understand the sarcasm, but it should have been [''] or '' as per the OP's requirement and I removed the reduce version :) Commented Jan 16, 2014 at 16:13

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.