cast an array in javascript

To cast an array in JavaScript, you can use Array.from() method. This method creates a new array instance from an array-like or iterable object.

index.tsx
const arrayLike = {0: 'a', 1: 'b', length: 2};
const arr = Array.from(arrayLike);

console.log(arr); // Output: ['a', 'b']
123 chars
5 lines

You can also pass a map function as the second argument to perform an operation on each element when casting the array:

index.tsx
const arrLike = {0: '1', 1: '2', length: 2}
const arr = Array.from(arrLike, x => parseInt(x));

console.log(arr); // Output: [1, 2]
132 chars
5 lines

Alternatively, you can also use the spread operator ... to cast an array:

index.tsx
const arrayLike = {0: 'a', 1: 'b', length: 2};
const arr = [...arrayLike];

console.log(arr); // Output: ['a', 'b']
116 chars
5 lines

related categories

gistlibby LogSnag