What is the best way to extract every nth digit from a number using a given reference point?

The subject of the title may cause confusion, so let me clarify my goal.

With values of n = 51 and m = 24, I aim to achieve this result:

[
    {start:0, end:24}, 
    {start:24, end:48}, 
    {start:48, end:51}
]

Currently, I have made progress on this task, but I am encountering issues with adjusting the j and end parameters.

var n = 51;
var m = 24;
var arr = [];    

for (var j = 0; j < n; j += m) {
  var end = (j + j) >= n ? n : j;

  console.log(j, end);

  if (j > 0) arr.push({
    start: j,
    end: end
  });
}

Any suggestions or solutions would be greatly appreciated!

Answer №1

The issue lies within the calculation for your end value. If the sum of j and m is greater than n, then you should set end to be equal to n.

var n = 51;
var m = 24;
var arr = [];

for (var j = 0; j < n; j += m) {
  var end = (j + m);

  arr.push({
    start: j,
    end: end > n ? n : end
  });
}

output.innerHTML = JSON.stringify(arr, null, 2)
<pre id="output"></pre>

Answer №2

let num1 = 51;
let num2 = 21;
let array = [];

for (let k = 0; k < num1; k += num2) {

  let final = k + num2 > num1 ? num1 : k + num2;

  array.push({
    start: k,
    end: final
  });

}

alert(JSON.stringify(array));

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 ES5 essentially the same as ES6 in terms of my lambda search?

After doing a search on an array using ES6, I am having trouble figuring out how to rewrite the code in ES5 due to restrictions with Cordova not allowing me to use lambda functions... $scope.Contact.title = $scope.doctitles[$scope.doctitles.findIndex(fu ...

Is it possible to verify whether a Node Js query is empty or not?

I've been attempting to determine if a result query is empty or not, conducting thorough research in the process. Below is the code illustrating the query I'm executing and the two methods I employed to check if it's empty. The issue at han ...

Populate the auto complete input box with items from a JSON encoded array

I have a PHP file that returns a JSON encoded array. I want to display the items from this JSON array in an autocomplete search box. In my search3.php file, I have the following code: <?php include 'db_connect.php'; $link = mysqli_connect($ho ...

What is the most efficient method for iterating through a 2-dimensional array row by row in PHP?

I have a 2D array and I need to insert multiple data into a table using a loop. Here is the data: $data['id'] = array([0] => '1', [1] => '2'); $data['name'] = array([0] => 'Ben', [1] => ' ...

Error message "Python numpy 'exceeds the number of indices for the array'" occurs when there

I am trying to store series of data from a data frame into a two-dimensional array. However, when I run the code below, I encounter an error stating 'too many indices for array'. Additionally, even after manually adjusting the shape of the array ...

I am in possession of a JSON file that lacks keys, and my objective is to extract the values and store them in a C# class object

Here is a JSON sample that I need to parse: [ [ 1617235200000, "58739.46000000", "59490.00000000", "57935.45000000", "58720.44000000", "47415.61722000", 1617321599999, &quo ...

Guide: Initiating an action in NuxtJs

I am attempting to trigger an action in my Vue component from my Vuex store. Below is the content of my aliments.js file in the store: import Vue from 'vue'; import Vuex from 'vuex'; import axios from 'axios'; Vue.use(Vuex, ...

Enable compatibility with high resolution screens and enable zoom functionality

My goal is to ensure my website appears consistent on all screen sizes by default, while still allowing users to zoom in and out freely. However, I've encountered challenges with using percentages or vh/vw units, as they don't scale elements prop ...

Issue with getStaticProps functionality on Vercel seems to be persisting

UPDATE: I realize now that my mistake was calling my own API instead of querying the MongoDB database directly in getStaticProps(). I have made the necessary changes: export async function getStaticProps() { await dbConnect(); const user = await User.find ...

The error message received was: "npm encountered an error with code ENOENT while trying to

About a week ago, I globally installed a local package using the command npm i -g path. Everything was working fine until today when I tried to use npm i -g path again and encountered the following error: npm ERR! code ENOENT npm ERR! syscall rename npm ER ...

Modifying a CSS property with jQuery

If I have the following HTML, how can I dynamically adjust the width of all "thinger" divs? ... <div class="thinger">...</div> <div class="thinger">...</div> <div class="thinger">...</div> ... One way to do this is usi ...

Tips on assigning html actions/variables to a flask submit button

I am facing an issue with my Flask app where the form submission process takes a while for the backend to process. In order to prevent users from refreshing or resubmitting, I want to display a loading gif during this time. The current HTML code for my fl ...

Getting rid of an Ajax loader graphic after a period of time

After a button is clicked, I have an ajax loader that appears and here is the code snippet: jQuery(document).ready(function($) { $('#form').on('submit', function() { $('#submit').css('display', 'bl ...

Transfer a GET parameter from the URL to a .js file, then pass it from the .js file to a

Hey there, I'm currently using a JavaScript file to populate my HTML page with dynamic data. The JS file makes a call to a PHP file, which then fetches information from my SQL database and echoes it as json_encode to populate the HTML page. The issue ...

Sending PHP output data to jQuery

Trying to implement this code snippet /* Popup for notifications */ $(document).ready(function() { var $dialog = $('<div></div>') .html('message to be displayed') .dialog({ ...

What is the best way to deploy a REST API utilizing an imported array of JavaScript objects?

I have been using the instructions from this helpful article to deploy a Node REST API on AWS, but I've encountered a problem. In my serverless.yml file, I have set up the configuration for the AWS REST API and DynamoDB table. plugins: - serverless ...

Implementing gridlines on a webpage using HTML and JavaScript to mimic the grid layout found in Visual Studios

Currently, I have a grid snap function in place, however, I am looking to add light grey lines horizontally and vertically on my Designing application. The goal is to achieve a similar aesthetic to Visual Studios' form designing feature. Utilizing so ...

Bootstrap modal's offset returning blank value

One way to navigate to a specific element within a Bootstrap modal is by checking the offset of that particular element. If there are multiple divs within the modal, each with its own unique id (#row-1, #row-2, etc.), you can open the modal and input the f ...

Using asynchronous JavaScript (AJAX) to request a file to be processed on the client-side

I have a query that I need help with: My goal is to retrieve a file from the server after it has undergone input-dependent processing through an AJAX request (such as using jQuery). However, I don't want to directly offer this file for download in th ...

Is your jquery keydown event detector failing to recognize key inputs?

Lately, I've been working on a new project and encountered an issue with a piece of code that used to work perfectly fine in a previous project. The code in question is $(document).keydown(function(keypressed){});, which I used to detect specific key ...