Form an array of numbers ranging from +10 to -10, with the middle number being 0, based on the desired length of the array

Is there a way to dynamically generate an array of a specific length without knowing its values in advance? For instance, if I need an array of 3 elements, it should be [-10, 0, 10], and for an array of 9 elements, it would look like [-40, -30, -20, -10, 0, 10, 20, 30, 40]. How can I achieve this automatically?

Answer №1

If you need to obtain the desired outcome, you can easily achieve it by utilizing the Array method in conjunction with fill

To ensure that only a 0 is at the center of the input, it is essential for the input to be of odd value.

const end = 9;
let start = Math.floor(end / 2);

const result = [
  ...Array(start).fill(0).map((_, i) => start * -10 + i * 10),
  0,
  ...Array(start).fill(0).map((_, i) => (i + 1) * 10)
]

console.log(result)

Answer №2

Here's an alternative approach using the Array.from method:

const generateArray = (size) => Array.from({length: size}, (element, index) => Math.round(index - size / 2) * 10);

console.log(generateArray(1))
console.log(generateArray(3))
console.log(generateArray(9))

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

Guide on how to halt camera animation in three.js when it reaches a specific position upon clicking

I'm currently working on a small piece of code that animates the camera to zoom in on an earth model when clicked. However, I'm facing an issue where I need to stop the camera animation once it reaches a certain position. Initially, the camera p ...

Tips for integrating Material UI Drawer with Redux

I have been attempting to incorporate a Drawer feature that displays on the left side while utilizing Redux to maintain the state of the Drawer. Unfortunately, I seem to have made an error as my onClick events are not responsive. Here is the code: Reduce ...

fancybox is slightly off-center

I am currently using fancybox 1.3.4 to display some content in a popup window, but I am facing an issue where the popup is not centered in the browser. Can anyone help me with fixing this problem? Here is the HTML code snippet: <a class="clickMe" titl ...

Why does the serial received message get saved in a character array?

Encountering a problem in my Arduino code when receiving a message from Serial. The issue arises when the message "START" is received via serial, triggering the execution of the function startSequence(). This function retrieves 8 values from a 2D matrix u ...

Undefined output in Typescript recursion function

When working with the recursion function in TypeScript/JavaScript, I have encountered a tricky situation involving the 'this' context. Even though I attempted to use arrow functions to avoid context changes, I found that it still did not work as ...

Cancel the shape that has been chosen on the canvas

My goal is to add a unique shape to the canvas using mouse events. To achieve this, I have set up a canvas where users can draw various shapes such as rectangles, circles, lines, and ellipses. A drop-down list has been created, containing all the shapes ...

Organize multiline string based on regex pattern using Javascript

I need to split a multi-line string and group it by a specific regex pattern that repeats throughout the text Some random filler in the beginning of the content Checking against xyz... Text goes here More text and more. Checking against abc... Another se ...

JavaScript along with Mongoose executes the for-loop prior to carrying out the .find operation inside

My partner and I are trying to calculate the average rating for each movie in our MongoDB database. We have two collections: Movie and Rating. Our approach involves retrieving all the movies first, then looping through each movie to find its corresponding ...

Interactive selection menu using PHP, MySQL, and JavaScript

Learn how to create a dynamic drop-down menu in PHP, MySQL, and AJAX that also includes an insert query for MySQL tables. Check out the code example below: <?php require('../conn/include.php'); require('quick.php'); $query="SELECT ...

Divide an Array into multiple String elements using JavaScript

Here is my array: ["John Connor ", "Mike ", "Ryan Jones ", "Markey O ", "Markey B"] I want to display each of these elements as separate strings, one below the other on the page. I tried using $(".info_container").text(myArray); but that just displayed t ...

Searching for values within dynamic JSON arrays can be done using the jQuery.InArray

My Ajax request is fetching a JSON array that looks like this: [101, 102]. These are image ids from a database. I am trying to display all the images on my page with a checkbox next to each one. If the image_id matches any in the array, I want the checkbo ...

Tips for merging an array with a timestamp column included

Within my PHP code, I am working with an array that looks like this: [ // 'Timestamp' => 'data', '1296001511 ' => '2', '1295994311' => '25', '1295965511' => '34&apo ...

The error middleware in Express is not defined

I'm facing an issue where the Express API error messages are returning as undefined on the frontend. This is preventing me from displaying proper error messages to alert users. Interestingly, the error messages seem to appear fine in the developer to ...

The div is set to a position of absolute, causing the overflow-y property to be set to auto. As a

I am facing an issue with a div that has absolute positioning nested inside other divs. If you take a look at the code snippet below from http://jsfiddle.net/d8GYk/, you'll notice the styling properties applied to the div. <div style="position: ...

Component experiencing issues with service or @Input functionality

I have been struggling with importing a service inside a component and encountering an issue where the Input from the service does not render anything in the template. Let's take a look at my entity: export interface PageState { step: string; } e ...

ReactJS and Redux: setting input value using properties

I am utilizing a controlled text field to monitor value changes and enforce case sensitivity for the input. In order to achieve this, I need to access the value property of the component's state. The challenge arises when I try to update this field ...

Extract HTML data from the parent window of a URL without relying on an Internet Explorer browser - Tracking UPS information for multiple packages

Could I be heading in the wrong direction with my JavaScript code? I am new to using VBA for internet data retrieval and struggling to find a solution. Currently, I have a working function that utilizes IE.doc but it's slow and requires waiting for br ...

The intricacies of a many-to-many relationship and how to populate associated data within a query when using Keystone

I'm currently working on a KeystoneJS project and encountering an issue with the relationships between two models. Here are the details of the two models: User model: User.add({ name: { type: Types.Name, required: true, index: true }, email ...

Creating a pointer to an array of strings in C++

Whenever I run this code, everything appears to function flawlessly string *s; s=new string("some_string"); *(s+1) = *s; However, if I substitute "some_string" with an empty string, my program encounters a segmentation fault. What could be causing this i ...

Error: Unable to assign value to property 'src' because it is null

Currently, I am attempting to display a .docx file preview using react-file-viewer <FileViewer fileType={'docx'} filePath={this.state.file} //the path of the url data is stored in this.state.file id="output-frame-id" ...