1

I'm trying to make an array of empty arrays, the amount of which depends on N. Currently, I have this:

var seqList = [];
for(var i = 0; i < N; i++) {
    seqList.push([]);
}

Is this the most efficient way of doing it? Or might there be another way?

3
  • 3
    Efficient in what way? Less code, better readable code, faster running code, etc.? Commented Sep 14, 2017 at 12:34
  • I was thinking faster running. I know it's not like it's horrendously slow, but if there was a huge value for N, I was just wondering if there was some method that would be a little faster that I don't know about. Commented Sep 14, 2017 at 12:39
  • 1
    Why are you optimizing something that you aren't positive needs optimization? Do some measurements first and see if any of the expected values for N actually cause problems and verify that this part of the code is the bottleneck, then proceed with ways to optimize. If you need to optimize this, I don't think there is a magical method that would make it much faster, unless you do a custom implementation and use a linked list. Commented Sep 14, 2017 at 12:51

2 Answers 2

2

Your method is the most efficient one. You can also use Array.fill method from ES6 but it is not the most efficient.

let n=10;
let array=Array.from({ length: n }, () => []);
console.log(array);

When you are using let array=[] you're telling the interpreter to create a new runtime array.

If you use:var a = new Array() you're telling the interpreterthat you want to call the constructor Array , generate an object and creating your array.

Sign up to request clarification or add additional context in comments.

Comments

0

Array#fill is the cleanest

let count = 10;
let seqList = Array(count).fill([]);

Update:

After being schooled by @deceze I would rather use since the example above fails is a horribly subtle way.

let count = 10;
let seqList = Array(count).fill(0).map(_ => []);

Is it better than your attempt? Probably not. I've just become so used to reading map/reduce, I prefer it. YMMV

4 Comments

seqList[0].push('foo')… try it.
@deceze Why would you need to push?. Per the question the size "depends on N"
Try. It. Then console.log(seqList). Then you'll see the problem with this approach.
@deceze. Very interesting. I've used it hundreds of times in production code and never had and issue. But then I usually map from it. Thanks for the heads-up

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.