Dividing a string in JavaScript to generate fresh arrays

I am currently dealing with the following string:

"ITEM1","ITEM2","ITEM3","ITEM4","ITEM5","ITEM6","ITEM7"~100000000,1000048,0010041,1,1,1,1~100000001,1000050,,2,0,2,1~100000002,1068832,0010124,1,1,1,1~100000003,1143748,0010165,1,1,1,1~100000004,,0010173,1,2,1,1~100000005,,0010199,2,2,2,1~100000006,,0010215,1,2,1,1~100000007,,0010306,0,2,1,1~100000008,1092546,0010355,1,1,1,1~100000009,1037977,,2,1,2,1~

My goal is to split this string by ~ and create separate arrays while adding double quotes "". The expected output should be as follows:

[
    ["ITEM1","ITEM2","ITEM3","ITEM4","ITEM5","ITEM6","ITEM7"],
    ["100000000","1000048","0010041","1","1","1","1"],
    ["100000000","1000048","0010041","1","1","1","1"],
    ["100000000","1000048","0010041","1","1","1","1"],
]   

This is what I have attempted so far:

str.split('~').slice(2)

Unfortunately, my current approach does not split the string into separate arrays. Any advice on how to achieve the desired outcome would be greatly appreciated. Thank you in advance.

Answer №1

You can start by splitting with the symbol ~, and then further split each subarray using the comma symbol ,. The code snippet provided also includes a step to remove any empty strings "". If you wish to keep them, simply omit the part .filter(i => i)

EDIT: The filtering for empty strings has been removed.

const s = '"ITEM1","ITEM2","ITEM3","ITEM4","ITEM5","ITEM6","ITEM7"~100000000,1000048,0010041,1,1,1,1~100000001,1000050,,2,0,2,1~100000002,1068832,0010124,1,1,1,1~100000003,1143748,0010165,1,1,1,1~100000004,,0010173,1,2,1,1~100000005,,0010199,2,2,2,1~100000006,,0010215,1,2,1,1~100000007,,0010306,0,2,1,1~100000008,1092546,0010355,1,1,1,1~100000009,1037977,,2,1,2,1~'

const arr1 = s.split('~')

const arr2 = arr1.map(arr => {
  arr = arr.replace(/\"/g, '')
  return arr.split(',')
})

console.log(JSON.stringify(arr2, null, 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

Is it possible to utilize Mouse hover to distinguish between various elements in React?

In an attempt to enhance this code, I wanted to make it so that when you hover over a specific element, another related element would also be displayed. Using useState in React seemed to be the most effective way to accomplish this after trying out a diffe ...

Express 4 Alert: Headers cannot be modified once they have been sent

I recently upgraded to version 4 of Express while setting up a basic chat system. However, I encountered an error message that says: info - socket.io started Express server listening on port 3000 GET / 304 790.443 ms - - Error: Can't set headers ...

Retrieve the item that is contained within a separate item within the original

Is there a way to access the Photos object in my code? I attempted to use {{ item.image.Photos[0].image }} but it was unsuccessful https://i.stack.imgur.com/IGC2c.png Looking for Assistance with TypeScript listHotelPhotos( hotel_id ){ let loader = t ...

Unable to modify the .top attribute style in elements within an arraylist using JavaScript

I need to align multiple images in DIVs on the same line by setting their Top value to match the first image in the array. Here is the code I am struggling with: (addBorder function is called when divs are clicked) <div class="DRAGGABLE ui-widget-cont ...

Adding a class to a clicked button in Vue.js

A unique function of the code below is showcasing various products by brand. When a user clicks on a brand's button, it will display the corresponding products. This feature works seamlessly; however, I have implemented a filter on the brands' lo ...

What is the most effective way to reduce the number of http requests caused by onChange events in Material UI Slider?

Is there a way to optimize my request handling? In my React project, I am currently utilizing Material UI's slider. With the onChange property, I am making HTTP POST requests whenever the slider is moved. Here is a snippet of the code: <Slider ...

"Learn how to trigger an event from a component loop up to the main parent in Angular 5

I have created the following code to loop through components and display their children: parent.component.ts tree = [ { id: 1, name: 'test 1' }, { id: 2, name: 'test 2', children: [ { ...

Generate a new array containing objects that possess distinct data types and identifiers, derived from the initial array of objects

Currently, I am working with an array that consists of various objects. Here is an example: const myDailyRutine = [ { event: "createdLetter", date: "2018-10-12T05:44:44.553216+00:00", user: { usernam ...

What is the best method for eliminating a character from all elements in jQuery classes?

I am working on an Angular 4 app where every .inner-page class in a html element includes a "/". For instance: <div _ngcontent-c0="" class="inner-page /login"> <div _ngcontent-c0="" class="inner-page /register"> I need to eliminate the "/" c ...

What is the process for obtaining a compilation of warnings from the next.js terminal?

While running my project on VScode, I noticed a series of warnings appearing in the terminal. One specific warning that caught my attention is: The `bg-variant` mixin has been deprecated as of v4.4.0. It will be removed entirely in v5. on line 8 ...

React-Native error message: Promise rejection unhandled - React child cannot be an object

I am experiencing an issue with rendering a list from an array of objects that have the structure provided below. While I have successfully handled the promise and set the data to the state, I keep encountering an error specifically with this array. The da ...

A guide on searching for information in a JSON document using PHP

In PHP, I am trying to retrieve an ID from the URL and then search for corresponding data in a JSON file, which will be displayed on the page. The URL structure will be and the code I will use is; $id = $_GET['id']; to assign the ID to a vari ...

Achieving CSS Buttons That Change to Green When Clicked and STAY Green

I've been tasked with working on a front-end project for a website that involves buttons changing color when clicked and staying that color. Here is the CSS <style> code I have written for these specific buttons: .button { background-color ...

Fade in background color with jquery when scrolling

Is there a way to make the header background fade in after scrolling a certain number of pixels? The code I have sort of works, but not quite right. Any suggestions? Thank you! $(function () { $(window).scroll(function () { $(document).scrol ...

ES6 Class Directive for Angular 1.4

I am currently exploring the possibility of incorporating a directive from version 1.4 and adapting it to resemble a 1.5 component. By utilizing bindToController and controllerAs, I aim to integrate the controller within my directive rather than using a se ...

Is there a way to display a Google Map marker after a certain amount of time without needing to refresh the

Is it possible to update Google Map markers without refreshing the map itself every 30 seconds? The markers' latitudes and longitudes are retrieved from a database. Once obtained, these markers are then allocated onto the Google Map. However, the i ...

Implement Material-UI's built-in validation for form submission

I'm in the process of setting up a form with validation: import React from 'react'; import { useForm } from "react-hook-form"; import axios, {AxiosResponse} from "axios"; import {Box, Button, Container, Grid, Typography} ...

how to display ajax response in webpage using jQuery

I need to perform multiple ajax calls in a for loop, with each call returning a text/html response that needs to be printed. Here is the code I have implemented: function printBill(printBills, lastBillNo, type,taxType,outletId,date){ var printableObjects ...

Setting character limits when defining string variables in TypeScript

Upon reviewing the documentation, it appears that there is no straightforward method to perform type checking for the minimum and maximum length of a string data type. However, is there a possible way to define a string data type using custom types in ord ...

Determine if the user has clicked on the Save or Cancel button within the print dialog box

Hello everyone, Can anyone help me figure out how to determine which button was selected by the user in a print dialog box? Thank you! ...