Populating an array in JavaScript with specific values from another array to meet a certain criteria

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);

Answer №1

You may have overcomplicated this task by using unnecessary steps. A simpler approach would be to either slice the array if no is less than arr.length, or push elements using the modulo % operator:

const animals = ['lion', 'tiger', 'cheetah', 'zebra'];
const animalArr = [];


function populateAnimalArray(arr, no) {

    if (no < arr.length) return arr.slice(0, no);
    
    for (let i = 0; i < no; i++) {
    
        animalArr.push(arr[i % arr.length]);
    }
    
    return animalArr;
}

const res = populateAnimalArray(animals, 14);
console.log(res);

Answer №2

Don't complicate things, just simplify

const animals = ['lion', 'tiger', 'cheetah', 'zebra'];
let newArr = [];
function populateAnimalArray(arr, no) {
  while (arr.length<no) arr = arr.concat(animals); // adding animals until the desired length is reached
  return arr.slice(0,no); // returning the array sliced to the specified length
}
newArr = populateAnimalArray([], 14)
console.log(newArr)
newArr = populateAnimalArray([], 3); // works for shorter arrays too
console.log(newArr)

Answer №3

One way to achieve this is by using the forEach array function.

const populateAnimalArray = (arr = [], nth) => {
    let newArr = [].concat(arr);
    while (newArr.length < nth) {
        arr.forEach(item => {
            if (newArr.length >= nth) {
                return
            }
            newArr.push(item);
        })
    }
    return newArr;
}

console.log(populateAnimalArray(['lion', 'tiger', 'cheetah', 'zebra'], 14));

Answer №4

You can utilize the array.from method to generate a fresh array containing various animals.

const animals = ['lion', 'tiger', 'cheetah', 'zebra'];
const populateAnimalArray = (animals, length) => {
  return Array.from({length}, (_,i) => animals[i%animals.length]);
}
console.log(populateAnimalArray(animals, 6));
console.log(populateAnimalArray(animals, 2));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №5

It's not functioning properly due to the array length exceeding the specified limit. Here's a solution to address this issue:

const animals = ['lion', 'tiger', 'cheetah', 'zebra'];
const animalArr = [];

function populateAnimalArray(arr, no) {
  arr.map(val => animalArr.push(val));
  let deficitElem; //
  if (animalArr.length < no) {
    deficitElem = no - animalArr.length;
    console.log('deficitElem', deficitElem);
    let j = 0;
    while(j < deficitElem) {
      for (let i = 0; i < animals.length; i++) {
        animalArr.push(animals[i]);
      }
      j += animals.length;
    }
  }
  console.log('animalArr', animalArr);
}

populateAnimalArray(animals, 14);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sort and incorporate elements by multiple strings present in an array

Looking to filter and include strings in an array by matching them with items in another array? Here is a sample code snippet that filters based on a single string: const filteredString = `${this.filter}`.toLowerCase(); this.filteredCampaigns = this. ...

Ways to resolve the error message "TypeError: 'setOption' is not a function on type 'MutableRefObject' in React"

CODE export default function EChart({ option, config, resize }) { let chart = useRef(null) let [chartEl, setChartEl] = useState(chart) useEffect(() => { if (resize) { chartEl.resize() } if (!chartEl.cu ...

Leveraging the power of Promise creation

I am facing an issue where I am trying to utilize the getPromise function with various URLs in order to obtain different promises, but encountering undefined values in the success function of the second promise. var http=require('http'); var URL ...

Utilizing an external API in Javascript for fetching data

Is it permissible for me to directly initiate an API request from JavaScript to an external API (in this scenario at ) using the XMLHttpRequest object? If not, what steps should I take to retrieve data from this source? Do I need to incorporate a PHP bac ...

The header() function triggers automatic page redirection instead of waiting for the form to be submitted

When I created a form that automatically sends an email upon submission, my goal was to direct the user to a thank you page after the email is sent. In my search for a solution, I stumbled upon the header() function in php and attempted to use it with the ...

Redux - The same reducers, containers, and components are yielding varying outcomes

update: Issue resolved by connecting a different variable to the mapStateToProps. I'm encountering some challenges with my react-redux application and I'm struggling to pinpoint the error in my setup. You can access the source code here. The f ...

Tips on ensuring that the Angular frontend waits for the response from an Express REST call

Upon initializing my user Component, I want to trigger a REST-Call so that the user profile is displayed when the page loads. The process works smoothly as the component communicates with the service, which in turn contacts my express backend to make the n ...

Troubleshooting problem: AJAX autocomplete URL returning XML

I found my code reference here: http://example.com/code-reference if ($hint=="") { $hint="<a href='" . $z->item(0)->childNodes->item(0)->nodeValue . "' target='_blank'>" . $y->item(0)->childNodes-> ...

Commit to persevering until you achieve success

I'm currently working with native node.js Promises and did not find any useful information in this thread. Essentially, I am dealing with a function that looks like this: var foo = foo (resolve, reject) { return obj .doA() .doB() ...

Tips on manually refreshing AngularJS view using ControllerAs syntax?

As I work on creating a user-friendly dashboard with widgets that can be sorted, docked, and floated, I encountered an issue. The controls I am using generate floating widgets as HTML at the bottom of the DOM, outside the controller scope where they were c ...

Navigating the grid layout in Material UI can be tricky to

I'm struggling to grasp the concept of the grid system in material UI. Within my grid container, I have two grid items that I want to be centered and occupy the entire width. The button element appears centered, but the typography element does not. A ...

Using a React component to send data through a POST request to an API

When attempting to send a selected value from a Dropdown to an API using a POST request, I keep encountering a 405 (Method Not Allowed) error. Despite trying different ways to handle the onChange event, such as: onChange{(e) => this.onChangeHandler(e.t ...

Error: Unable to assign a value to the statusCode property because it

During the development of my application backend, I encountered an error while working on the user login route. When testing the route using Postman, I received the following error message: UnhandledPromiseRejectionWarning: TypeError: Cannot set propert ...

Creating a distinct header value for every $http request

I've been assigned the task of adding a unique ID for each request to all HTTP requests made by our AngularJS application for logging purposes. While this is more crucial for API calls, I'm currently working on implementing it for all kinds of re ...

Utilize pg-promise for inserting data with customized formatting using the placeholders :name and :

After reviewing the pg-promise documentation, I came across this code snippet: const obj = { one: 1, two: 2 }; db.query('INSERT INTO table(${this:name}) VALUES(${this:csv})', obj); //=> INSERT INTO table("one"," ...

Finding the value of an input without having to submit it first and searching for it within a datalist

> Here is an example of HTML code <label>Person</label> <input name="PersonID" type="text" id="PersonID"> <label>Car Plate Number</label> <input name="PersonsCarPlateNumber" list="PersonsCarPlateNumbe ...

I'm experiencing an issue when trying to align TextPath to the center in an SVG file - a certain character

When using the startOffset or text-anchor attributes, I noticed that some characters are missing. How can I fix this issue? Thank you. It appears that in this scenario, the characters `1234` are missing. <svg xmlns="http://www.w3.org/2000/svg" versi ...

Develop an exclusive "click-once" button for a webpage

Can anyone assist me in creating a "one-time clickable" button to launch my website? I've searched through numerous threads on Stack Overflow but haven't found a solution yet. ...

The use of callback functions with Model.findOne() in Mongoose is now deprecated, and will result

Think about this: app.get("/posts/:postId", function(req, res) { const requestedPostId = req.params.postId; Post.findOne({_id: requestedPostId}, function(err, post) { res.render("post", { title: post.title, content ...

Steps for initiating a $.ajax POST request from a client to a server

Currently, I am working on a phonegap application where I need to transfer some data from an HTML file to a server and receive a response in return. Everything works fine when all the files are on the same server. However, once I separate the files between ...