Guide to dividing an array into smaller arrays whenever a designated value is detected in JavaScript

What is the best way to divide an array at the occurrence of the word 'split' and generate smaller sub arrays?

This is a sample representation of my current array:

const myArray = ['abc', 'xyz', 123, 'split', 'efg', 'hij', 456, 'split'];

This is how I envision the transformed array:

const newArray =[['abc', 'xyz', 123], ['efg', 'hij', 456]];

In addition, I have stored the indexes of the word 'split' in an array like this:

const splitIndex = [3, 7];

Answer №1

To achieve the desired outcome, one can loop through the splitIndex array and slice the original array up to that particular index.

const
    data = ['abc', 'xyz', 123, 'split', 'efg', 'hij', 456, 'split'],
    splitIndex = [3, 7],
    result = [];

let i = 0;

for (const j of splitIndex) {
    result.push(data.slice(i, j));
    i = j + 1;
}

console.log(result);

Answer №2

let array = ['hello', 'world', 123, 'split', 'goodbye', 'moon', 456, 'split'];

const bar = (arr, separator) => {
    let tempArray = [];
    const finalArray = [];
    arr.forEach(value => {
        if (value !== separator) {
            tempArray.push(value);
        } else {
            finalArray.push(tempArray);
            tempArray = [];
        }
    })
    return finalArray;
}
console.log(bar(array, 'split'));

result:

[ [ 'hello', 'world', 123 ], [ 'goodbye', 'moon', 456 ] ]

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 there is no blank space between the bootstrap labels when using ng-repeat

When using ng-repeat in Angular.js to add labels, they appear without spacing. Check out this Plunker for a demonstration. However, if I add labels manually by copying the HTML code, they are displayed with whitespace. Is there a way to add white space b ...

Tips for selecting each item from an array in their own sequence? (using jQuery and JavaScript)

Here's my code: I've come to understand that my for loop assigns all array elements to the variable pickSound, hence it only plays the last element. How can I modify it so that each element plays in order and starts over once finished? functio ...

Using Python to generate a value based on text input that is stored in arrays

Although I am fairly new to python coding, I am eager to generate an output based on several factors. Let me try to elaborate as best as I can. There are 6 different zones: ZONE = ["RED", "GREEN", "BLUE", "YELLOW", "PINK", "WHITE"] For example purposes, ...

Navigating the world of date pickers: a deceptively easy challenge

Take a look at this fiddle example to get started: http://jsfiddle.net/1ezos4ho/8/ The main goals are: When a date is selected, it should be dynamically added as the input value, like <input type text value="date selected".... Update: <s ...

TextGeometry in Three JS is designed to always face the user

Here is the source code I have been working on. My main goal is to make sure that TextGeometry is always facing the camera. Is this possible? Code: var stats; var camera, controls, scene, renderer; init(); render(); functi ...

When I trigger the onSubmit function, I encounter difficulty in displaying the current state

I am using a component that is rendered four times in the parent component. I want to update the state in the parent component and display an array with values from all four inputs. However, when I submit the form in the parent component, the state doesn ...

"Storing a collection of PDF files in an array in TypeScript Angular - A step-by-step

Here we have an HTML code snippet that includes an input file element with Angular: <input type="file" class="btn btn-info" id="archivoPDF" #PDFfile value="Seleccionar PDF(s)" accept="application/pdf" multiple /> And this is the TypeScript code sni ...

Enhance Canvas when React State Changes

I am currently working on integrating a canvas into my React project. The main goal is to overlay styled text (with custom font color, style, and size) on an image. I've set up a basic form to input the styling attributes and the desired text. Whenev ...

express.js loop execution timing issue

My current code is not waiting for the loop to finish before printing {"personalchats":[]} I need to send after the for loop has completed. How can I fix this issue? connection.query("SELECT * FROM personalchat WHERE user1ID = ? OR user2ID = ?", [userID, ...

Sending an AJAX request will only transmit a portion of an array when using the JSON.stringify

I have a JavaScript array that is constantly updated. Here's how I initially set up the array... columnArray = ["userID", "Date", "trialType", "cue", "target", "response", "accuracy", "lenAcc", "strictAcc", "fkpl", "totalTime"]; var dataArray = []; ...

Passing retrieved REST data from service file to AngularJS controller

Hey everyone, I'm new to angular js and running into an issue with sending data from my service file to the controller, which is then supposed to be displayed in my HTML. Could someone please provide some guidance on how to solve this problem? Thank y ...

Regular expression "or" found within the express route string that includes an express parameter

I'm attempting to achieve this, but it's not functioning as expected. app.get("/|/:enter"); I would like to have one app.get route that covers both / and /:enter. update Both app.get("/|/:enter"); as well as app.get("/:enter|/"); do not p ...

steps to activate button once the form is validated

Can you provide guidance on disabling and enabling a button when the form is valid? I have several conditions in my form: Name on Card: Should only contain English alphabetic letters. Card Number: Must consist of exactly 16 numbers. Expiration Month: A ...

Is anyone able to identify the issue in this code?

Currently, I am tackling a challenge that involves taking parameters such as nums, row, and column to produce a resulting matrix of size row x column. def matrixReshape(self, nums, r, c): """ :type nums: List[List[int]] :type r: int :type ...

Can you explain the significance of Pageset to me?

I've been searching online but haven't found a definitive answer yet. Can someone explain the concept of Pageset to me? When someone mentions including code in Pageset, what exactly are they talking about? ...

Repositioning objects within a 2-dimensional array using C语言

I am working with a 2D array filled with random numbers. Here is an example: #define d 4 int main(void) { int a[d][d]; int primary[d], secondary[d]; size_t i, j; srand(time(NULL)); /* fill array with random numbers */ for (i = 0; i < d; i++) for ...

Geoserver does not have the 'Access-Control-Allow-Origin' header

map.on('singleclick', function (evt) { document.getElementById('info').innerHTML = "Looks like you need to redo this :) !!!"; var view = map.getView(); var viewResolution = view.getResolution(); var source = hcm.getSource(); var url = s ...

Prevent users from submitting the form again within the last 7 minutes after they have already clicked the Submit button

I am looking to implement a feature where the 'Submit' button is disabled for 7 minutes. During this time, I want a message displayed next to the form that says: "Wait 7 minutes before submitting". Once the countdown is complete, I would like the ...

Is it possible to share a variable between different scopes in an Angular environment?

As I dive into building my first real Angular.js application, focused on assisting judges during courtroom hearings, I am encountering various challenges and learning how to overcome them. The application consists of views such as Calendar, Documents, and ...

Retrieving data from MySQL using PHP and AJAX with radio button selection

How can I update my code to display data from the database when a radio button is clicked instead of using a drop-down box? Here is an example of my current radio button code: <Input type='Radio' Name='compcase' value='1'/& ...