5

I am a bit confused by the behavior of Array.map function here:

var arr = ['one', 'two', 'three'];
var result = '';
result += arr.map(function(elm) {
    return elm;
});

// 'one,two,three'

How does it automatically join the returned results with a , ?

Note: This only happens if I concatenate the returned result in a string.

3 Answers 3

13

Array.map did nothing to your array.

You basically did this

'' + ['one', 'two', 'three']

Which calls the toString() method of an array, whose default behaviour is to join(',') the array.

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

Comments

5
var arr = ['one', 'two', 'three'];
var result = '';
var r = arr.map(function(elm) {
    result = result + ' ' + elm;
    return elm;
});
alert('r-> ' + r);
alert('result-> ' + result);

It is because the arr.map function is returning after processing each element in array and not for individual elements as you are expecting to append to 'result' variable. If you wish to concatenate values to 'result' variable, you should do so inside the map function for each element instead. And as Sirko said, the commas are coming from the toString() method. Check the above code on jsfiddle here: http://jsfiddle.net/qt3nryLq/

Reference to Array.map(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

1 Comment

stackoverflow.com/a/16607599/3177115 ... is a very elegant solution
2

The commas stem from the toString() method of Array and not the map() function!

var arr = ['one', 'two', 'three'];

arr.toString(); // 'one,two,three'

var result = '';
result += arr.map(function(elm) {
    return elm;
});

result.toString(); // 'one,two,three'

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.