A custom function designed to apply a specific skipping pattern to an array, resulting in a modified array being returned

I am looking to create a skip pattern that can be applied to an array. The goal is to select the starting point of the pattern within the array and then return the items based on that pattern.

For instance, if I want to skip 2 2 1 2 in the array arr = [1,2,3,4,5,6,7,8,9], starting from the second item (2), it should return [2,4,6,7,9]. Does anyone have insight into how this can be achieved using JavaScript?

Answer №1

Give it a shot

let testArray = [1,2,3,4,5,6,7,8,9];
let jumpPattern = [2,2,1,2];

console.log(sliceArray(testArray, jumpPattern));

function sliceArray(arr, pattern){
    for(let i = 0; pattern.length > i; i++)
        arr.splice(i, pattern[i] - 1);    
    return arr;
}

Answer №2

In the world of arrays, it is common for them to be zero-indexed. Therefore, stating that the start index is two may seem a bit strange since it actually corresponds to the third element in the array. However, you can use a function like the one provided below to get yourself started.

function extractElements (start, pattern, arr)
{
    let currentIndex = 0,
        resultArray = [ ];

    pattern.unshift (start == 0 ? start : start - 1); // This tweak is made to handle the situation where the first index in the array is considered as the second element. If that's not needed, simply use pattern.unshift(start);

    for (let value of pattern) {
        currentIndex += value;
        resultArray.push(arr[currentIndex]);
    }

    return resultArray;
}

The above code will produce:

=> extractElements(2, [2, 2, 1, 2], [1, 2, 3, 4, 5, 6, 7, 8, 9]);
[2, 4, 6, 7, 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

Ensure the browser back button navigates to the login page seamlessly, without displaying any error

A scenario I am working on involves a Login jsp that accepts a user email and sends it to a servlet. If the provided email is not found in the database, the servlet redirects back to Login.jsp with an attribute "error". Within the header of Login.jsp, ther ...

Get string variables that are specified in an array by matching a specific pattern

The unique parameter "$@" consists of the string variables below: echo $@ shows: a.bdf, b.bdf, c.nas, d.nas I am interested in isolating the string variables with the 'bdf' extension and storing them in a separate array. Can this be achieved u ...

Dealing with a JavaScript Problem on Wordpress Using AJAX

Struggling with transitioning a website from Drupal to WordPress, I encountered an issue with a page that utilizes AJAX. A user followed a tutorial on implementing AJAX using JavaScript, PHP, and MySQL. Even though the AJAX functionality works fine on Drup ...

Automatically submitting a form in React.js based on certain conditions being met

Does anyone have experience with React login and register form buttons that trigger Redux actions? I'm facing an issue where both actions are being dispatched at the same time when certain conditions are met. Here is my code snippet: const LoginPage ...

What is the equivalent of console.log(obj) for retrieving object properties?

When obtaining an object using mongoose, named doc, there is a property owner:{} that appears when doing 1console.log(doc)1. However, this property disappears when using doc.toJSON() or doc.toObject(). How can I retrieve this property without using for(p ...

Steps for refreshing a React component following a data fetch operation

Currently, I am in the process of learning how to use React for building web applications. I have a basic React app that demonstrates the following features: Fetching a list of users Displaying the names of the users on individual cards once they are fetc ...

Issue with retrieving data from controller in Spring MVC 3 using jQuery and AJAX via $.get method. The value is not being returned to the

I am currently diving into the world of AJAX, particularly in conjunction with Spring MVC. However, I am encountering some challenges along the way. Before delving into my actual real-time project requirements, I decided to test out the AJAX+Spring MVC+jQ ...

Determining the total number of combinations possible from a collection of five arrays containing items

I have five massive collections filled with various strings, and each of them contains a different number of elements. Below are examples of the lists: List 1 "Jeffrey the Great", "Bean-man", "Joe", "Charles", "Flamur", "Leka", ...

Unable to trigger click event on dynamically appended div

I have integrated Google Place Autocomplete into my project. Upon searching in the autocomplete textbox, Google dynamically adds some divs to the HTML structure. <div class="pac-container" style="position: absolute; z-index: 1000; width: 134px; left: ...

Memory leaks observed in BinaryJS websockets

Currently, I am in the process of developing a simple client/server setup to facilitate the transfer of image data between a browser and a node.js server using BinaryJS websockets. Despite following the API examples closely, it seems that my implementatio ...

Using multiple unique markers on Google Maps

Currently trying to grasp the concept of creating a customized Google map. I have limited experience with javascript but I'm eager to learn. I found some code online that helped me understand how to add locations, markers, and infowindows, but now I ...

Anticipating the execution of pool.query within a callback function in the Express framework

Within an Express post endpoint, I am utilizing crypto.generateKeyPair. After generating the key pair, I wish to store it in my database and then return the ID of the inserted row within the same endpoint. Here is the code snippet for the endpoint: app.p ...

Error Uploading File to Cloudinary Platform

I am currently developing a REST API using Express.js. The main functionality of the API involves accepting a video file from the client and uploading it to Cloudinary. Interestingly, when I test the API by returning the file back to the client, everything ...

Ways to Organize the Results in a Function

Here's what I have attempted: read -p "Enter City In Australia: " city function getaa { curl -s http://localhost:8080/api/examples-services/postcode/$city/ | json_pp | grep -E '"' | cut -d \ -f7-30 | cut -d: -f1 | tr -d &ap ...

The hovering effect on the image link is causing the surrounding div to stretch too far

Whenever I hover over specific points below an image link wrapped in a div, it triggers the hovering effect for the CSS-created image link. Despite trying various solutions like overflow:hidden and display:inline-block, nothing seems to resolve this issue. ...

Creating an Interactive Table Using HTML, JavaScript, and PHP?

After reviewing this project, I am looking to customize the js function in relation to my own table. The key focus is on the following code: $("#employee_table tr:last").after("<tr id='row"+$rowno+"'><td><input type='text&apo ...

Foundation Unveil Modal hidden from view

I'm currently integrating modals using Foundation 5 in a Rails application. The issue I'm facing is that the modal only works when the page is not scrolled down. If you scroll to the bottom of the page and try to activate the modal by clicking ...

Guide to generating a dropdown menu in PHP with an array of choices

Seeking a solution for a seemingly simple question, but struggling to make it work! I need to access an array within a function by concatenating the passed ID with "_array" as part of the variable name. How can I achieve this referencing another variable? ...

Issue with Node.js xml2js module: Sitemap attributes are not being recognized during creation

Currently, my project involves utilizing node.js and xml2js to generate an XML sitemap.xml. Everything seems to be in order, but when I try to define attributes like: '$': { 'xmlns': 'http://www.sitemaps.org/schemas/sitemap/0 ...

What is the process for running a script during partial view rendering?

My view is strongly typed to a CalculateModel where a user inputs information and then makes an ajax post to the controller. The controller performs calculations using this data and returns a PartialView strongly typed to the ResultCalculateModel. The Res ...