I am trying to create a recursive buildList()
function that takes any value and adds it a number of times (the length
argument) to an empty array. The code I have so far (which uses array.concat(value)
) can add anything except blank arrays (it can even add empty objects).
var buildList = function(value, length, i = 1, array = []) {
if (i > length) {
return array;
} else {
return buildList(value, length, i 1, array.concat(value));
}
};
console.log(buildList([], 4));
//output = [], when I want it to be [[],[],[],[]]
CodePudding user response:
You can use Array.from
instead. Note that unless you want the resultant array to hold the same reference multiple times, you'll want to provide a callback function to return the value to fill with for non-primitives.
const buildList = (value, length) => Array.from({length},
_ => typeof value === 'function' ? value() : value);
console.log(buildList(() => [],4));
console.log(buildList("test", 3));
CodePudding user response:
The issue is that when you run array.concat()
with two arrays, the array is not pushed to the end of the other, but its contents are added together. Try using .push()
instead.
var buildList = function(value, length, i = 1, array = []) {
if (i > length) {
return array;
} else {
array.push(value);
return buildList(value, length, i 1, array);
}
};
console.log(buildList([], 4));
//output = [], when I want it to be [[],[],[],[]]
Note that your code does not make deep copies of the object passed. This means that if you change one of the elements, then all the elements will change too. If you don't want that to happen, then you can use this code:
var buildList = function(value, length, i = 1, array = []) {
if (i > length) {
return array;
} else {
array.push(structuredClone(value));
return buildList(value, length, i 1, array);
}
};
console.log(buildList([], 4));
//output = [], when I want it to be [[],[],[],[]]