1

I was surprised to discover flattening behavior of String constructor when applied to an Array.

Why does this work. And is this a good way to flatten an Array?

Tested to same results on Mac Chrome, Safari, Firefox.

String(['a', 'b', ['c', 'd', ['e', 'f']]])

=> "a,b,c,d,e,f"
4
  • It doesn't flatten, then the result would be ['a','b','c','d','e','f'] or the desired result "abcdef" Commented Feb 14, 2019 at 17:31
  • 2
    its not a good way to flatten an array. what if one of the strings included a comma? Commented Feb 14, 2019 at 17:32
  • 1
    Why not use array.flat when it's already supported in most of major browser Commented Feb 14, 2019 at 17:34
  • alert(String(['a', 'b', ['c', 'd', ['e', {erm:'notsogood'}]]])); Not a good way. Are you assuming all arrays are going to be characters? Commented Feb 14, 2019 at 17:36

4 Answers 4

6

Because converting an array to a string will call .toString which is basically the same as calling .join(), which will call .toString onto all elements in the array, and then delemit the result with a comma. Therefore the arrays get recursively joined to a string, the result looks flattened as there is no indicator for the start or end of the array. Here is the conversion step by step:

 [[1, 2, 3], [1, 2, 3]].toString()
 [1, 2, 3].toString() + "," + [1, 2, 3].toString()
 (1 + "," + 2 + "," + 3) + "," + (1 + "," + 2 + "," + 3)
 "1,2,3" + "1,2,3"
 "1,2,3,1,2,3"
Sign up to request clarification or add additional context in comments.

1 Comment

This is correct. Array.prototye.toString() internally calls Array.prototype.join(). You can read about details here
4

It calls Array.prototype.toString - that is all.

1 Comment

The source you link to doesn't mention the recursive behavior.
1

It doesn't flattern an array, it makes a string out of an array. For better options check out Array.flat or, for example, some libraries like lodash flattern() (or Underscore or Rambda).

Comments

1

It is not the only way to convert an array into a string. Often JSON.stringify is preferred:

const arr = [1,[2,[3]]];
console.log(JSON.stringify(arr));

The reason why it seems to 'flatten' the list is that it String is being called recursively on the whole array:

const arr = [1,[2,[3]]];

console.log(
  String(arr)
);
console.log(
  String(arr[0]),
  '+ , +',
  String(arr[1])
);
console.log(
  String(arr[0]),
  '+ , +',
  String(arr[1][0]),
  '+ , +',
  String(arr[1][1])
);

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.