Converting other data types to arrays Flashcards
1
Q
Converting a string to an array:
A
let str = ‘Hello World’;
let arr = Array.from(str);
console.log(arr);
// outputs: [ ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’ ]
2
Q
Converting an object to an array:
A
let obj = { name: ‘John’, age: 30 };
let arr = Object.entries(obj);
console.log(arr);
// outputs: [ [ ‘name’, ‘John’ ], [ ‘age’, 30 ] ]
3
Q
Converting a number to an array:
A
let num = 12345;
let arr = Array.from(num.toString());
console.log(arr);
// outputs: [ ‘1’, ‘2’, ‘3’, ‘4’, ‘5’ ]