Create Array with Array.from()
Write a JavaScript function that takes a string and returns an array of its individual characters using Array.from(). The Array.from() static method creates a new shallow-copied array from an iterable or array-like object.
Array.from() is a static method that converts iterable or array-like objects into arrays. Unlike str.split('') which also splits a string into characters, Array.from() correctly handles Unicode characters that consist of two UTF-16 code units (like emoji). It also accepts an optional map function for transforming elements during creation.
Array.from() can create arrays from: strings, Set, Map, NodeList, TypedArrays, and any iterable with Symbol.iterator. It is more robust than spread operator for array conversion because it works with array-like objects that don't have Symbol.iterator.
Time complexity is O(n) where n is the string length. Space complexity is O(n) for the resulting array. Array.from() creates a new array without modifying the source string.
Edge cases include empty strings (returns empty array), single-character strings, strings with special Unicode characters, and ensuring each character becomes a separate array element.
Example Input & Output
Split into characters
Single character
Digits as characters
Simple string
Empty string
Algorithm Flow
Solution Approach
Convert a string into an array of characters using Array.from(). This method creates a new array from an iterable object like a string. Each character of the string becomes an element in the resulting array.
Array.from() works with any iterable, making it useful for converting strings, sets, maps, and array-like objects into true arrays. The spread operator [...s] achieves the same result.
Time complexity is O(n), space complexity is O(n).
Best Answers
function solution(str) {
return Array.from(str);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
