How can I fill the empty slots of a sparse array with values (e.g. undefined)?
let array = ['a',,,,'z']
// Should return
['a', undefined, undefined, undefined, 'z']
This will fill it up :
let array = ['a',,,,'z'];
Array.from(array);
// Returns ['a', undefined, undefined, undefined, 'z']
[...array]You can spread the array and you will get undefined in the previously empty slots
let array = ['a',,,,'z']
const result = [...array];
console.log(result);
// ['a', undefined, undefined, undefined, 'z']
for(let i = 0; i < array.length; i++) {
test("array ", array, i);
test("result", result, i);
}
function test(name, arr, num) {
console.log(`${num} in ${name}: ${num in arr}`);
}
.as-console-wrapper {
max-height: 100% !important;
}