What is the quickest method to populate an array with numerous values in JavaScript? Is there a way to utilize a pattern or function with the fill method instead of a single value in JavaScript?

Is there a way to create an array of a specific size (for example, 10) and populate it with numbers following a specified pattern (such as 1, 2, 3 or 2, 4, 6) in just one line using JavaScript?

let arr = new Array(10).fill((a) => {a = 1; return a++;});
console.log(arr); // Expected output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

In other words, is it possible to pass a pattern or function to the `fill` method instead of a single value?

Answer №1

If you're looking for a more elegant way to generate ranges in JavaScript, consider using the spreaded Array constructor:

[...Array(n)]

This will create an array filled with n undefined values. To get the range 0..n-1, simply access its keys:

[...Array(n).keys()]

For more complex ranges, you can utilize the map function:

r = [...Array(10)].map((_, i) => i + 1)

console.log(r)

For further information on this topic, check out: Does JavaScript have a method like "range()" to generate an array based on supplied bounds?

Prior to this method, another option was using Array.from:

r = Array.from({length: 10}, (_, i) => i + 1);

console.log(r)

The `from` method inspects the length property of its first argument (which can be any object), and then iterates from 0 to length - 1, calling the second argument with a value parameter that is undefined unless the object has corresponding numeric properties, along with an index parameter from 0 to length - 1. In this case, we use a function that returns the index + 1, resulting in a sequence from 1 to length.

To simplify the process, here's a handy wrapper function:

let range = (from, to) => Array.from({length: to - from + 1}, _ => from++);

console.log(range(1, 10))

Alternatively, for ES5 compatibility, you can use Array.apply(null, {length:N}):

r = Array.apply(null, {length: 10}).map(function(_, i) {
    return i + 1
})

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

The ng-model does not reflect changes when using the JQuery datepicker

Currently, I have set up two textboxes for users to choose a date. I am utilizing JqQuery's datepicker UI to showcase a small calendar pop-up whenever the user clicks on the textbox. However, an issue arises when I select a date in the calendar popup ...

MongoDB ratings are failing to update as anticipated

I'm currently working on incorporating a rating system similar to upvotes and downvotes. Users have the ability to vote on a lesson only once. They can change their votes between up and down. If they vote the same as their previous vote, it cancels ou ...

Manipulate DIVs by sliding them and resizing their contents with JQuery

Can someone help me with sliding the top div up and down, and the left div left and right? I wrote some code for this but seem to be facing some issues. When I slide the left div, the center content falls down momentarily. Additionally, the code doesn&apos ...

How can I activate a jQuery function only when it is within the viewport?

I have installed a jQuery Counter on my website, but I am experiencing an issue where the counter starts or finishes before reaching the section where the HTML code is embedded. Any assistance with this problem would be greatly appreciated! <script& ...

jQuery .click() function doesn't seem to be triggering as anticipated

My goal is to create an interactive functionality where: When a user clicks on the h4 element inside a .question divThe .question div expands to a height of 90px, and its child paragraph slides into view with a margin-top of 0If the user clicks the h4 el ...

Passing the state variable from a hook function to a separate component

I have a hook function or file where I need to export a state named 'isAuthenticated'. However, when I try to import this state using import {isAuthenticated} from '../AuthService/AuthRoute', I encounter an import error. My goal is to m ...

Is there a method to match the items in an array that can remove itself after use? (Secret Santa Matching Tool)

I am working on developing a Secret Santa program. The program is designed to prompt for at least three names initially, and then ask if there are any more names to add. If the user provides more names, another text field will open up to accommodate them. ...

What steps can be taken to extract data from an axios call within a computed method for further manipulation?

Utilizing an axios call, I retrieve data in the following format: export default { name: 'TaxesSection', data () { return { isFormShown: false, isLoading: false, isOpen: false, info: n ...

Is there a way to eliminate span tags from elements?

I need to replace all the span tags with the class "article" and add new span tags to the content <div class="asd"> <span class="location">Foo</span> <span class="article">bar</span> <span ...

send data to pop-up using POST method

I am facing an issue while trying to send a variable to print on a modal. I keep getting the error Notice: Undefined variable: ordID Despite searching through several sources, none of the solutions seem to work for my problem. This is my code: Table with ...

When using VueJS, clicking on one button will automatically disable all other remaining buttons

Currently, my setup involves three buttons displayed using a v-for loop, each with its own click method. I'm trying to implement a feature where clicking on one button disables the others, but also allows clicking on the active button to re-enable al ...

Experiencing difficulties with retrieving form data in req.body using Express and node.js

I am facing an issue while trying to create a registration form for new users with profile picture upload. Despite adding body-parser middleware, the form data is not passing correctly to the route and I cannot identify the reason behind it. Error: D:&bso ...

Step-by-step Guide to Setting pageProps Property in Next.js Pages

When looking at the code snippet provided in .../pages/_app.js, the Component refers to the component that is being exported from the current page. For instance, if you were to visit , the exported component in .../pages/about.js would be assigned as the ...

Running a Node.js script on an Express.js server using an HTML button

I've got an HTML button: <button id="save" type="button" onclick="save()">Save</button> and in my JavaScript code, I want it to execute something on the server side using node.js Here's what I have in mind: function save() { / ...

How can I receive a callback for loop playing in Cordova media?

In my Angular JS service, I am utilizing the cordova media plugin to access media files. MediaSrv.loadMedia(filePath, mediaSuccess, null, status).then(function(media, status, test, status1){ media.play({ numberOfLoops: 999 }); ...

Exporting variables in Node.js using module.exports

I am facing an issue with two JavaScript files, a1.js and utils.js. Here is the content of the files: a1.js const namet = require('./utils.js') console.log(name); utils.js console.log('utils.js'); const name ='Mike'; modul ...

What is the best way to gather user input and incorporate it into a selected template, ensuring it is verified before sending?

I'm in the process of developing a project that involves gathering user input through a collector and displaying it on my template for verification before sending it out. The format I'm aiming for can be seen here: This is the template format I ...

Why is my jQuery click event not triggering when I click the div element?

After reviewing my code multiple times, I realize that I may have made a rookie mistake. Some of the things I've tried include adding div before .select-delete, and using document.write("Hello") to check if the event was triggering. If you want to ta ...

How to deliver various static files in NestJS using different paths and prefixes?

I've set up static file serving for developer documentation using the following code: app.useStaticAssets(docsLocation, { prefix: "/docs/" }) Now I have another directory with more static content that I want to serve. Is it possible to serve from ...

Issue with vue-template-compiler in Vue.js 3 webpack configuration

I am currently working on integrating vuejs 3 into a project that already utilizes webpack. I have been looking into using vue-loader as part of this process. After consulting the official documentation, I came across the following information: Every new ...