I'm looking for an implementation of createEmpties(nValues) as below:
var result = createEmpties(4);
console.log(result)
[[], [], [], []]
I tried using map:
new Array(nValues).map(_ => []);
but got this output:
[ <4 empty items> ]
You can do it using Array.from.
const result = Array.from({ length: 4 }, () => []);
console.log(result);
const result = Array.from({ length: 4 }, () => []); result[2].push("hello"); console.log(result); const result1 = new Array(4).fill([]); result1[2].push("hello"); console.log(result1); Array.fill fills object reference not creating new instance.Array.fill.The new Array, will not fill. Try Array(nValues).fill(null).map(_ => []). This should give you what you are looking for.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill
const result = Array.from({ length: 4 }, () => []); result[2].push("hello"); console.log(result); const result1 = new Array(4).fill([]); result1[2].push("hello"); console.log(result1); Here's a function that gives you exactly what you asked for:
function createEmpties(n) {
return Array(n).fill(new Array());
}
var result = createEmpties(4);
console.log(result)