Say you have an array-like Javascript ES6 Iterable that you know in advance will be finite in length, what\'s the best way to convert that to a Javascript Array?
The
Array.from()
function, it takes an iterable as in input and returns an array of the iterable....
in combination with an array literal.const map = new Map([[ 1, 'one' ],[ 2, 'two' ]]);
const newArr1 = [ ...map ]; // create an Array literal and use the spread syntax on it
const newArr2 = Array.from( map ); //
console.log(newArr1, newArr2);
Be cognizant of the fact that via these methods above only a shallow copy is created when we want to copy an array. An example will clearify the potential issue:
let arr = [1, 2, ['a', 'b']];
let newArr = [ ...arr ];
console.log(newArr);
arr[2][0] = 'change';
console.log(newArr);
Here because of the nested array the reference is copied and no new array is created. Therefore if we mutate the nested array of the old array, this change will be reflected in the new array (because they refer to the same array, the reference was copied).
We can resolve the issue of having shallow copies by creating a deep clone of the array using JSON.parse(JSON.stringify(array))
. For example:
let arr = [1, 2, ['a', 'b']]
let newArr = Array.from(arr);
let deepCloneArr = JSON.parse(JSON.stringify(arr));
arr[2][0] = 'change';
console.log(newArr, deepCloneArr)