Retrieve portions of an array with a dynamic starting point

I was attempting to extract a subset of array elements based on a range of values.

Consider the following array:

const arr = ["one", "two", "three", "four", "five", "six", ...]

If I wanted to retrieve only the first four elements, I would use the following code:

arr.slice(0, 4)
// output: ["one", "two", "three", "four"]

Now, what if I wanted the next four elements instead? In other words, how can I achieve this output:

// output: ["five", "six"]

Furthermore, I aim to make this process dynamic by using a function like this:

// first set of data (first four)
getData(1)
// second set of data (next four)
getData(2)

Is there a way to accomplish this task?

Answer №1

For your getData function, consider using the slice method with (num - 1) * 4 as the starting index and num * 4 as the ending index:

const arr = ["one", "two", "three", "four", "five", "six"]

function getData(offset) {
  return arr.slice((offset - 1) * 4, offset * 4);
}

console.log(getData(1), getData(2));

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

Swap out a specific section of a canvas with an image

My current challenge involves replacing a section of an HTML canvas with an image. The goal is to set a background image on the canvas with solid colors, such as red, and then iterate over the pixels of the image. If a pixel matches the color red, it shoul ...

Vue.js - Maintaining input value when model declines updates

I am working on a text input that allows users to enter numbers with a maximum of three digits after the decimal point: <v-text-field type="text" :value="num" @change="changeNum($event)" /> <p>{{ num }}</p> ... export default { data: ...

Steps for successfully passing an object in a dynamically generated function invocation

In my jQuery script, I have a click event bound to thumbnail images with the class "thumbnail": $(".thumbnail").click(function(){ var obj = new Object(); obj.el = "imageEdit"; obj.id = $(this).attr("id").replace("img_",""); openDialogue(obj); }); ...

The sequence of text is not appearing correctly

I'm attempting to populate a paragraph with JSON data, while inserting a divider between data gathered on different dates. function fetchAllLogs(employeeId) { $.getJSON('datafile.json', function(data) { $("#" + employeeId).html( ...

"Encountered a mysterious issue with Electron's ipcMain

An issue arises when executing the code below: const ipcMain = require('electron').ipcMain; ipcMain.on('open-file-dialog', function (event) {}); The following error message is displayed in the console: Uncaught TypeError: Cannot read ...

Having trouble with NPM Moment.js in React: Why is moment__WEBPACK_IMPORTED_MODULE_2__format not functioning properly?

scenario, After resolving my current issue using dateFns (date-fns.org), I am interested in integrating Momentjs into the project as well. The task at hand involves converting data to a string format within an app built with create-react-app. However, wh ...

The array value will remain as 0 when printed, even if it has been modified in C

I recently created a custom data type called typedef unsigned char byte;, and proceeded to declare an array of this type by using byte mem[255];. To initialize the first value, I used mem[0] = 0x10100000;. However, when I attempt to print this value usin ...

Passing a one-dimensional array into std::thread is not possible

This example is derived from my current project, but I have created a simpler version for demonstration purposes (inspired by Lightness Races in Orbit). #include <thread> #include <iostream> class Foo { Foo(int n = 10) { size_ ...

Success message displayed for Ajax form submission, yet email delivery remains pending

In my PHP code for sending emails, I have a function called "Send to friend" that works perfectly with standard PHP post. This confirms that the sendtomail.php file is functioning correctly as well. /* AJAX Code for Send to Friend */ $(function() { $(&ap ...

A guide on implementing the intl-tel-input plugin within an Angular 2+ project

Component : ng2-tel-input, Framework : Angular 4, JavaScript library : intl-tel-input Upon completing the installation with npm i ng2-tel-input I stumbled upon a note in the node_modules\intl-tel-input\src\js\intlTelInput.js file that ...

Navigating arrays using pointers - permissible yet ambiguous actions

Wondering if these lines of code could potentially result in undefined behavior in both C and C++, I delved into the standard regarding array subscripting (C 6.5.6 - 8) to find some answers. The explanation is quite lengthy, so I'm summarizing here. ...

What is the best way to refresh a div every 20 seconds?

I'm currently working with this script: <script id="_wauwgs">var _wau = _wau || []; _wau.push(["small", "p00ystfryeuc", "wgs"]); (function() {var s=document.createElement("script"); s.async=true; s.src="http://widgets.amung.us/small.js" ...

"Calling getElementByID results in a null value being returned (see example in the provided

In my attempt to design unique buttons for a media player, I encountered a challenge. I envisioned the play button transitioning into a "loading" button and eventually into a pause button. My solution involved using 4 div elements - stop, play, loading, a ...

When attempting to import a component from react-bootstrap, an error is thrown

Every time I try to use a component from 'react-bootstrap', I encounter a strange error. Here is a small example where I am importing the "HelpBlock" component. import PropTypes from 'prop-types'; import React from 'react'; i ...

When the web driver fails to function as expected

After installing the selenium-webdriver via npm, I downloaded the IE component from this link and added it to my path on Windows 8. Upon opening IE, I had to set all security zones to high, ensuring they were consistent. However, due to restrictions in th ...

Assistance requested in structuring JSON data

I'm currently working on making my javascript code more dynamic. Here's what I have so far: data.addRows(2); data.setValue(0, 0, 'name goes here'); data.setValue(0, 1, value 1 goes here); data.setValue(0, 2, value 2 goes here); data. ...

Running React Boilerplate with forever is a great way to ensure your application stays

I plan on keeping the react-boilerplate application running indefinitely on the server. I recently came across forever, but I'm uncertain about how to pass parameters to it. The command to start the server looks like this: PORT=80 npm run start:produ ...

"MongoDB fails to save changes when attempting to remove an item from an updated

I've been using Angular Fullstack for a web application. When I send my data using $http.post(), I include the following object: { title: "Some title", tags: ["tag1", "tag2", "tag3"] } However, when I edit the object and try to update it with $http ...

Error: webpack is failing to load the style and CSS loaders

I'm currently experimenting with the FullCalendar plugin from fullcalendar.io. They recommended using Webpack as a build system, which is new to me. I managed to set up the calendar functionality after some research, but I'm facing issues with th ...

Display the source code of an HTML element when clicked

Is there a way to show the source code of an element on a webpage in a text box when that specific element is clicked? I am wondering if it is feasible to retrieve the source code of an element upon clicking (utilizing the onClick property), and subseque ...