1

This should be very basic but do not working. I am trying to push an element on 2d number array on a specific index, but it is inserting element on every index.

let adj = new Array(4).fill(new Array())

adj[0].push(1)
console.log(adj)

The output I am getting:

[[1], [1], [1], [1]] 

But I am expecting:

[[1], [], [], []]
7
  • [].constructor([1],[],[],[]); Commented Aug 23, 2022 at 12:00
  • @NajamUsSaqib why? just why? yes it gets to the right result but still, why? Commented Aug 23, 2022 at 12:02
  • @Amit, how big is your array? is there a reason you use new Array(4).fill(new Array()) instead of [[], [], [], []]? Commented Aug 23, 2022 at 12:04
  • @Thomas developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Aug 23, 2022 at 12:04
  • @Thomas I want a dynamic 2d array where length is fixed for main array. But all internal array size is dynamic. If I be very specific, I want to create a adjacency list for a graph where each array index means the node number and each index(node) will contant the node which has path/connection to it. Commented Aug 23, 2022 at 12:09

1 Answer 1

4

What you're doing with let adj = new Array(4).fill(new Array()) is just setting adj to an array of references to the same array, thus changing one, changes the others.

To fix this do it like this

let adj = Array.from(Array(4), () => new Array());
adj[0].push(1);
console.log(adj)

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

3 Comments

@Marco Thanks for your workable code. But I have one more confusion then. Why I need Array.from where this is already an array.
Because if you try to fill the already existing array it will be filled with references to the same object. When using Array.from the arrow function argument () => new Array() is called for every element, thus creating a list of unique arrays. In other words creating a 2D array.
@Marco ok from your idea, finally I have got another two ways. let adj = new Array(4).fill(null).map(() => []) let adj = [...new Array(4)].map(() => [])

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.