Convert a Set, Map or string to an array in JavaScript
Beginner ยท 3 min read
Arrays have the best tools in JavaScript: map, filter, sort, join and many more. Other collections, like a Set, a Map or a string, don't have most of them. So a common first move is to turn the thing you have into an array, then use the array methods on it.
In this tutorial you will turn a string, a Set, a Map and an "array-like" object into arrays with Array.from. You will also find the one case where the spread syntax [...x] can't do the same job, and see why a string with an emoji in it is not quite a row of characters. You should know what an array is. Everything else is explained below.
Iterables and array-likes
An iterable is anything you can walk through one item at a time with for...of: arrays, strings, Sets and Maps are all iterable.
An array-like is a plain object that has a length and numbered keys, like { length: 2, 0: 'a', 1: 'b' }. It looks like an array but has none of the array methods, and it is not iterable. You meet these in older browser code.
Array.from accepts both kinds. The spread syntax only accepts iterables. That is the whole difference this exercise is about.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
4 Turn other things into arrays
easyUse Array.from on a string, a Set, a Map and an object with a length. Then find the one of those four that spread syntax cannot handle.
Stuck? Three hints, smallest first
- 1. Spread needs an iterable.
Array.fromalso accepts an array-like: any object with a numericlength. - 2. A
Mapiterates as[key, value]pairs. - 3. A string iterates by code point, but
.lengthandsplit(โโ)count UTF-16 units.
Step 1: a string
A string is iterable, so Array.from walks it one character at a time.
const chars = Array.from('Lagos');
console.log(chars); // [ 'L', 'a', 'g', 'o', 's' ]
Step 2: a Set
A Set holds each value once. Copying it into an array keeps that de-duplicated list, and now you can sort it or map over it.
const unique = Array.from(new Set([1, 1, 2, 3]));
console.log(unique); // [ 1, 2, 3 ]
Step 3: a Map
A Map stores key and value pairs. When you walk a Map, each item is a small array: [key, value]. So the copy is an array of pairs.
const pairs = Array.from(new Map([['a', 1], ['b', 2]]));
console.log(pairs); // [ [ 'a', 1 ], [ 'b', 2 ] ]
Step 4: an array-like
Array.from reads the length, then reads keys 0, 1, 2 up to that length.
const arrayLike = Array.from({ length: 3, 0: 'a', 1: 'b', 2: 'c' });
console.log(arrayLike); // [ 'a', 'b', 'c' ]
Step 5: where spread gives up
Spread works for the first three. Try it on the array-like:
console.log([...'Lagos'].length); // 5
console.log([...new Set([1, 1, 2])]); // [ 1, 2 ]
try {
[...{ length: 2, 0: 'a', 1: 'b' }];
} catch (e) {
console.log(e.constructor.name); // TypeError
}
Spread needs something it can walk with for...of. The array-like has a length but nothing that tells JavaScript how to walk it, so you get a TypeError. Array.from has a fallback for this case; spread does not. That makes the array-like the one of the four that spread can't handle.
Step 6: a string is not a row of characters
Here is a surprise. Text inside JavaScript is stored as small pieces called code units. Ordinary letters take one each. Many emoji take two.
const withEmoji = 'a๐b';
console.log(withEmoji.length); // 4
console.log(withEmoji.split('').length); // 4
console.log(Array.from(withEmoji).length); // 3
console.log(Array.from(withEmoji)[1] === '๐'); // true
console.log(withEmoji.split('')[1] === '๐'); // false
length and split('') count code units, so they see four, and split('') cuts the emoji into two broken halves. Array.from (and spread) walk the string by code point, which keeps each emoji whole, so they see three.
One more limit to know about: some emoji, like flags or a family, are made of several code points joined together. Those still come apart with Array.from. Splitting those correctly needs Intl.Segmenter, which is beyond this exercise.
The full solution
The panel converts all four values, shows the spread error, and compares the three ways of splitting 'a๐b'. Press Run to see the output.
const chars = Array.from('Lagos');
const unique = Array.from(new Set([1, 1, 2, 3]));
const pairs = Array.from(new Map([['a', 1], ['b', 2]]));
const arrayLike = Array.from({ length: 3, 0: 'a', 1: 'b', 2: 'c' });
// The array-like has a length but no Symbol.iterator, so spread refuses it.
const spreadArrayLike = (() => {
try { return [...{ length: 2, 0: 'a', 1: 'b' }]; } catch (e) { return e.constructor.name; }
})();
const withEmoji = 'a๐b'; // three code points, four units
console.log('string :', chars);
console.log('Set :', unique);
console.log('Map :', pairs);
console.log('array-like :', arrayLike);
console.log('spreading the array-like:', spreadArrayLike);
console.log('--- a string is not a row of characters ---');
console.log('Array.from :', Array.from(withEmoji), Array.from(withEmoji).length);
console.log('.length :', withEmoji.length);
console.log("split('') :", withEmoji.split('').length, '<- the emoji came apart');
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a string splits into characters', chars, ['L', 'a', 'g', 'o', 's']);
test('a Set drops the duplicate', unique, [1, 2, 3]);
test('a Map arrives as key/value pairs', pairs, [['a', 1], ['b', 2]]);
test('an object with a length works', arrayLike, ['a', 'b', 'c']);
test('but spreading it throws, because it is not iterable', spreadArrayLike, 'TypeError');
test('from() walks a string by code point', Array.from(withEmoji).length, 3);
test('while length counts UTF-16 units', withEmoji.length, 4);
test("and split('') cuts the emoji in half", withEmoji.split('').length, 4);
test('the halves are not the emoji', withEmoji.split('')[1] === '๐', false);
Array.from and spread are close but not interchangeable. Spread requires an iterable; Array.from also accepts an array-like, which is any object with a numeric length. That is what you need for the arguments object in older code, and for a NodeList in browsers that predate its iterator.
The string assertions are the ones to remember. split('') cuts by UTF-16 unit and will happily produce half an emoji; Array.from and spread iterate by code point and do not. Neither respects grapheme clusters, so a flag or a family emoji still comes apart โ for that you need Intl.Segmenter.
Common mistakes
- Using spread on an array-like. It throws a
TypeError. UseArray.fromwhen you aren't sure the value is iterable. - Expecting a Map to become a list of values. You get
[key, value]pairs. UseArray.from(map.values())if you only want the values. - Using
split('')on text people type. It breaks emoji in half. UseArray.from(text)or[...text].
Try it yourself
- Turn
new Map([['x', 1], ['y', 2]])into an array of just its keys. - Use
Array.fromwith a second argument to turn'123'into[1, 2, 3]in one call. - Count the letters in
'hรฉllo๐'with.lengthand withArray.from. Explain the difference.