Creating a custom increment array in JavaScript from 0 to N

Issue Description

I am attempting to create an array utilizing the keys() and .map() techniques, based on a preexisting array with a length of arrLength, so that only elements at positions which are multiples of step are produced. See the example below,

const arrLength = 20;
const step = 5;

const newArr = [...Array(arrLength).keys() ].map((i) => i + step);

console.log(newArr) ;
// expected: 0,5,10,15,20
// received : 5,6,7,...,24

I am specifically unsure about how to increment the variable i in the function map((i) => ... ).

Constraints

I aim to accomplish this task in a single line using the keys method along with Array and possibly map, avoiding the use of a for loop.

Tried Approaches

I have attempted the following variations as well

    Array(arrLength).fill().map((_, i) => i+step) ,
    Array.from(Array(arrLength), (_, i) => i+step),
    Array.from({ length: arrLength }, (_, i) => i+step)

but without success. I also tried to figure out a way to increment the i variable using functional syntax but did not succeed either.

Answer №1

Let's create an array with a length of 20 and a step of 5. We start with an empty array and loop through the desired range, incrementing by the step value each time to push the values into the array. Finally, we log the resulting array to the console.

Alternatively,

A different approach is to use the spread operator along with the Array keys method to generate a new array with the specified length and step size. By mapping over the created keys, we calculate the values based on the step and log the new array to the console.

Answer №2

range function works with ES4 Using Array.from allows you to work with objects that have a property length in them

const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
console.log(range(0, 20, 5))

Answer №3

While browsing, I stumbled upon this interesting code snippet and decided to experiment with it. Essentially, it generates an array with incrementing numbers, but the functionality can be easily expanded.

The function provided utilizes the reduce method to create the desired array by using the index i of each element. It then combines the current result (stored in variable a) with the incremented value of i.

const arr = new Array(52).fill(0).reduce((a,_,i) => [...a, i],[])

Answer №4

Although this post may be dated, have you considered trying this approach instead?

let increment = 5;
const numbers = Array.from({length: 10}, (_, i) => i * increment);

console.log(numbers);

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

Is it possible for JavaScript to capture scroll events while allowing clicks to pass through?

Currently, I have a setup where the user needs to interact with the layer behind the transparent scroll capture: http://jsbin.com/huxasup/4/edit?html,css,js,console,output scrollerCapture = document.querySelector('.scroller-capture'); scrollerC ...

Fade in effect using AJAX when submitting a form

Hey there, I have a question regarding a fade out div. So, when using facebox and getting an error message after submitting, it displays this link: But, I want that message to fade away once it's been acknowledged. In my AJAX handler for the form sub ...

Leveraging JavaScript functions within an HTML file on an Android device

Currently, I am facing an issue with loading and playing videos via streaming in my Android app using a JavaScript code inside an HTML file. My approach involves using a WebView to showcase the video content. However, the challenge lies in the fact that th ...

Fetching and storing external data into an array using AngularJS

I'm attempting to retrieve data from a database using an external script in order to populate a select dropdown. However, my current approach results in numerous empty li elements being generated. Although the count seems correct, nothing is actually ...

Is it common in Node.js to create multiple instances of "server" objects, but only connect one to a port?

After finishing "Node.js in Action", I'm now piecing together the concepts of Node.js, Connect, and Express. My inquiry revolves around the creation of servers in Node. node_server = http.createServer(); connect_app = Connect(); express_app = Express ...

Retrieving data from multiple arrays using JavaScript

I have an array of hex colors. $.each(["#FF0000", "#000", "#FF6600", "#00E641"], function(i, c) { $('<input class="btns" type="button">') .css("background-color", color) .on("touch", $.proxy(funcNew, null, color)) .appendTo(" ...

Is it better to convert fields extracted from a JSON string to Date objects or moment.js instances when using Angular and moment.js together?

When working on editing a user profile, the API call returns the following data structure: export class User { username: string; email: string; creationTime: Date; birthDate: Date; } For validating and manipulating the birthDate val ...

Utilizing enum values as a data type for efficiency

Having an enum called AudioActionTypes: export enum AudioActionTypes { UpdateMusicData = 'UPDATE_MUSIC_DATA', UpdateVoiceData = 'UPDATE_VOICE_DATA', UpdateSoundData = 'UPDATE_SOUND_DATA', } There is a function that disp ...

Utilize AngularJS to bind keys to arrays

Hey there, I have an array that looks like this: $scope.Selectedgroups =[183,184,24] I want to convert it to the format shown below: [{groupId:183},{groupId:184},{groupId:24}]; I've been trying to convert it using a for loop: var groups=[] ...

Tips for circumventing CORS in an ajax request using various browser extensions or add-ons

I am encountering a cross-origin problem with my WCF service. Despite adding an extension in chrome to bypass CORS, the issue persists. Is there any other extension/add-on/plugin available to test the service locally and bypass the CORS problem? Edit Aft ...

Using synchronous XMLHttpRequest on the main thread is no longer recommended when working with embedded JavaScript in code

I've implemented a basic Ajax function on my website, but I'm encountering a warning in the console. The warning states: Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's expe ...

Angular services Eclipse Mars JavaScript validation

When using Eclipse validator, it seems that the keywords "finally" and "catch" are not allowed: $http.get(url) .success(function (data) { // Handle data }) .error(function (data, status) { // Handle HTTP error }) .finally(function () { // Ex ...

Compel a customer to invoke a particular function

Is there a way to ensure that the build method is always called by the client at the end of the command chain? const foo = new Foo(); foo.bar().a() // I need to guarantee that the `build` method is invoked. Check out the following code snippet: interface ...

Audio support across multiple channels on iOS and Android web browsers

After stumbling upon a helpful link to a page here on StackOverflow discussing "Creating Audio using Javascript in <audio>", and also finding a resource on another website detailing how to play audio on multiple channels, I have come across a questio ...

Placing an unchanging array between alternating columns

If I have a matrix that is M x N, how can I easily insert a constant column vector of size M x 1 (with all 1's) in between each of the N columns? The resulting matrix would then be of dimension M x (2*N-1), with every other column containing just 1&ap ...

Error in C++: Exceeding Defined Boundaries

I am facing an issue with pushing a specific struct from my private class into a vector of the same class type records. Although I successfully retrieve the variable data in my main function, I keep encountering an out of bounds error when attempting to co ...

Issue with resetting input forms in ReactJS

I have a simple form that seems to be clearing the rest of the fields every time I try to fill it. Additionally, validation errors are being displayed below each field instead of just one. How can this issue be fixed? Here is how the form looks before any ...

Using Vue.js to showcase real-time Pusher data in Laravel 5.4

I am currently working on developing a real-time chat application using vue.js, Pusher, and Laravel. I have successfully managed to receive information from Pusher, as I can view the JSON data in the console with the correct details. However, I am facing a ...

What is the reason behind the linking or appearance together of src/pages in Visual Studio Code?

As I venture into the world of Visual Studio Code (VSC) and follow a Gatsby tutorial, I've noticed that every time I create a new directory, VSC seems to automatically link src/pages together. However, my preference is for pages to be a subfolder of s ...

Having trouble playing the correct audio files from the array

I am facing an issue where when I tap on any cell in my table view, they all play the same song from the first array. How can I ensure that each cell plays the song assigned to its individual array? The function automaticPlay() is responsible for handlin ...