Looking to implement a function called populateAnimalArray
, which takes an array as input and populates it with additional elements based on another argument specifying the required number.
const animals = ['lion', 'tiger', 'cheetah', 'zebra'];
const animalArr = [];
populateAnimalArray(animals, 6);
// Expected output: ['lion', 'tiger', 'cheetah', 'zebra', 'lion', 'tiger']
The current implementation provided below does not work correctly in all scenarios:
const animals = ['lion', 'tiger', 'cheetah', 'zebra'];
const animalArr = [];
function populateAnimalArray(arr, num) {
arr.forEach(val => animalArr.push(val));
let missingElem; //
if (animalArr.length < num) {
missingElem = num - animalArr.length;
console.log('missingElem', missingElem);
for (let i = 0; i < missingElem; i++) {
animalArr.push(animals[i]);
}
}
console.log('animalArr', animalArr);
}
populateAnimalArray(animals, 14);