I am seeking to divide an array into multiple arrays, each based on the presence of a specific element from a separate array

Is there a way to split an array into multiple arrays based on specific elements from another array?

For example, take the following situation:

var test = ["1","2","3","env","6","7","8","uat","2344","wersdf","sdfs"];
var test2=["env","uat"];

In this case, we would like to create a mapping as follows:

{
env:["6","7","8"],
uat:["2344","wersdf","sdfs"]
}

It is important to note that the elements in test2 and test1 can vary. Additionally, the two values from test2 may not be consecutive in the test array; other items may be interspersed between them.

Answer №1

You may find Array#Reduce handy

  1. Start by looping through the test2 array and match the index of test
  2. Proceed to use a for loop with the initial value as ind+1. This will target the next delimiter argument
  3. Add the value to an array using acc[b].push()
  4. Detect the next delimiter by using test2.indexOf(test[i]) == -1 in the else condition. At this point, you need to break the statement and begin with the second argument of test2

function mapper(test, test2) {
  return test2.reduce((acc, b) => {
    let ind = test.indexOf(b); //find starting index of delimiter
    if (ind > -1) {
      acc[b] = acc[b] || []; 
      for (var i = ind+1; i < test.length; i++) {
        if (test2.indexOf(test[i]) == -1) { //detect reaching the next delimiter
          acc[b].push(test[i])
        }else{
         break;
        }
      }
    }
    return acc
  }, {})
  
}

var test = ["1", "2", "3", "env", "6", "7", "8", "uat", "2344", "wersdf", "sdfs"];
var test2 = ["env", "uat"];

console.log(mapper(test, test2))

Answer №2

const items = ["apple", "banana", "orange", "grapes", "kiwi"];
const fruitsToCheck = ["orange", "grapes"];

const indexes = [];

fruitsToCheck.map(fruit => {
  const index = items.indexOf(fruit);
  indexes.push(index);
})

const result = {};
for(let i = 0; i < indexes.length; i++){
  const part = items.slice(indexes[i] + 1, indexes[i+1]);
  result = {...result, [fruitsToCheck[i]]: [ ...part]};
}
console.log("Resulting object is: ", result);

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

Retrieving and securely storing information using fetch() on authenticated REST services

Currently, I have successfully set up a React application that communicates with a REST backend which is built using Python and Flask. The specific functionality I have achieved involves downloading data from a database and saving it as a CSV file through ...

Ajax calls for validations are failing to trigger a response from PHP

I am currently working on validating my signup form using PHP and AJAX, but unfortunately, I am not receiving any response value. Below is the AJAX code snippet I am using: <script type="text/JavaScript"> function frmValidation(str) { ...

Can I access VueSession in main.js for Vue.js?

In my main.js file, I have set up the following configuration: import Vue from 'vue' import App from './App.vue' import VueRouter from 'vue-router' import Home from './views/Home.vue' import Login from './views/ ...

End jQuery animation

My website has a feature where users can create, edit, or delete news items using AJAX controls. A small message is displayed at the top of the page to confirm their actions. For example, if a user adds a new post, a message saying "Added News: title" pops ...

Contrasting the Next 12 client-side routing with the Next 13 server-centric routing

According to the Next 13 documentation, it explains how the new router in the app directory utilizes server-centric routing to align with Server Components and data fetching on the server. Unlike the traditional pages directory that employs client-side r ...

Leveraging Google Analytics with Angular 4 and beyond

Having trouble integrating Google Analytics with Angular 4? Can't seem to find the @type for ga.js in ts? Here's a quick fix that I implemented in every component: declare let ga: any; How did I solve it, you ask? I created a function to dyna ...

Trouble with NodeJS: Unresponsive after AJAX post

Using NodeJS/Express with jQuery on the client side, I attempted to send a JSON object to the NodeJS/Express server for further processing. However, instead of receiving the expected "Hello World" message from the exports.findApiData function in index.js, ...

Restore the onblur attribute after deleting it

I am facing an issue with a textbox that utilizes onblur and ondblclick events. When the user double clicks, it triggers a pop-up screen but I do not want the onblur event to be activated. To prevent the onblur event from triggering when double-clicking, ...

Organize subarrays within an array in Mongoose

I am dealing with mongoDb data that looks like this: [{ "_id": { "$oid": "57c6699711bd6a0976cabe8a" }, "ID": "1111", "FullName": "AAA", "Category": [ { "CategoryId": { "$oid": "57c66ebedcba0f63c1ceea51" }, "_id" ...

Display the webpage following a successful XMLHttpRequest POST request

I'm struggling with rendering a page following an XMLHttpRequest POST. Here's what I have on the client side: var http = new XMLHttpRequest(); var url = window.location.origin + "/mypath"; http.open("POST", url, true); //Include necessary hea ...

Is there a way to access and read all JSON files within a directory in a Meteor application?

Is there a way to read all JSON files within a folder in my Meteor application? This is the structure I currently have: /server -- /methods -- -- file1.json -- -- file2.json I've attempted to read all JSON files using this code snippet: var ...

Using AngularJS to show/hide elements within a colgroup tag

Looking to create a dynamic table allowing users to hide certain columns. Wondering if it's possible to use ng-show with colgroup or col tags instead of adding ngshow to each cell individually. Struggling to make it work... <colgroup ng-repeat="mt ...

Retrieve the hidden input's value and set it as the value of another input

There is a hidden input that I am working with: <input type="hidden" id="hidden" /> $('#hidden').before('<input type="text" id="mhidden" alt="decimal" value="" />'); var val = $('#hidden').val(); $('#mh ...

Display different icons in an Angular application based on the value received from an API in real

My goal was to create a dynamic form that displays icons for the fields I have created. Here is a snapshot of my UI screen showing the field explorer with the list coming from an API. https://i.sstatic.net/4Ye9G.png I need to place an icon in front of ea ...

What methods are available to transfer a variable from one component to another in React?

In my React app, I have a form component that interacts with a PostgreSQL database to send data. Here is the script for my form: import bodyParser from 'body-parser'; import React, { Fragment, useState } from 'react'; import RatingStar ...

Initialization of Arrays with Default Values

I have taken on the task of converting a C++ program into JavaScript. In C++, when creating a dynamic array of type float/double, the entries are automatically initialized to 0.0; there is no need for explicit initialization. For example, a 1-D vector of ...

Transferring information between two components in separate Angular 4 modules

Within my application, I have defined two modules named AppModule and UserModule. I am currently encountering an issue with data sharing between the AppComponent and the LoginComponent (which belongs to the UserModule). Below is a snippet of app.componen ...

OpenAI gym throws an IndexError when attempting to use arrays as indices that are not of integer or boolean type

I've been putting my skills to the test with an OpenAI Gym project lately. While coding to tackle a particular environment, I keep encountering an error stating "IndexError: arrays used as indices must be of integer (or boolean) type", which seems to ...

In TypeScript, what is the return Type of sequelize.define()?

After hearing great things about TypeScript and its benefits of static typing, I decided to give it a try. I wanted to test it out by creating a simple web API with sequelize, but I'm struggling to understand the types returned from sequelize. Here ar ...

Trouble with Twitter Bootstrap tooltip functionality

After downloading Twitter Bootstrap and including the .js files in the footer, I wanted to implement a tooltip that appears when users mouse over an info icon. Here is the code snippet I used: <img src="<?php bloginfo('template_directory') ...