0

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']
0

2 Answers 2

3

This will fill it up :

let array = ['a',,,,'z'];
Array.from(array);  
// Returns ['a', undefined, undefined, undefined, 'z']
Sign up to request clarification or add additional context in comments.

5 Comments

Nice and clean, but spread syntax will be significantly more performant than Array.from(). [...array]
@pilchard I get 1529 ops/sec for spread syntax and 1514 ops/sec for Array.from. I wouldn't call that "significantly" more performant. It's 0.7% better. Re-ran the tests a few times and the results were similar each time. The widest difference I got was 1536 ops/sec for spread syntax vs 1494 ops/sec for Array.from. Which is a 2.8% increase. I'd still hardly call it "significant".
@VLAZ I initially ran the benchmarks on Safari which shows a whopping 200% increase from Array.from to Spread. But in Chrome I get results closer to yours.
@VLAZ, which tests do you run and how do you run them, to get those numbers?
@BenDak the ones linked by pilchard : measurethat.net/Benchmarks/Show/13243/0/arrayfrom-vs-forof-vs scroll down and you'd see a "Run tests" button: i.imgur.com/9hvQNN8.png
2

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.