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

Obtaining the "match" object within a Custom Filter Selector on jQuery version 1.8

Here's a helpful resource on Creating a Custom Filter Selector with jQuery for your reference. A Quick Overview: If you're unfamiliar with jQuery's Custom Filter Selectors, they allow you to extend jQuery’s selector expressions by addi ...

Array Filtering with Redux

I have come across similar queries, but I am still unable to find a solution. While typing in the search box, the items on the screen get filtered accordingly. However, when I delete a character from the search box, it does not show the previous items. For ...

Enhance a React component by including additional properties when passing it into another component through props

I have a parent element with a dynamically changing height that I need to pass down to its child elements. To get and set the height of the parent element, I am utilizing a ref. The challenge lies in passing this height value from the parent component to ...

What methods are available to generate dynamic shapes using HTML?

Looking to create an interactive triangle where users can move vertices or sides, updating angles in real-time. I'm struggling with how to accomplish this task. My initial attempt was to manually draw the triangle using the code below. <!DOCTYPE ht ...

When I delete the initial element from the array, the thumbnail image disappears

Using react-dropzone, I am attempting to implement image drag and drop functionality. The dropped image is stored in the React state within a files array. However, a problem arises when removing an image from the array causing the thumbnails of the remain ...

Concentrating on div elements using React

Can the focus() method be used to focus on a div element or any other elements? I have added a tabIndex attribute to a div element: <div ref="dropdown" tabIndex="1"></div> When I click on it, I can see that it gets focused. However, I am att ...

Just initiate an API request when the data in the Vuex store is outdated or missing

Currently, I am utilizing Vuex for state management within my VueJS 2 application. Within the mounted property of a specific component, I trigger an action... mounted: function () { this.$store.dispatch({ type: 'LOAD_LOCATION', id: thi ...

Storing user input in MongoDB after encoding

I am currently exploring the most effective methods for storing and presenting user input in MongoDB. In traditional SQL databases, it is necessary to encode all user input as a precaution against injection attacks. However, in the context of MongoDB, ther ...

What steps should I follow to effectively store this JSONB data in PostgreSQL by utilizing node-postgres (pg)?

After receiving information in the GET URL, I need to pass it into JSON format and save it with increasing IDs into a PostgreSQL database. However, the code I wrote does not seem to be saving anything without any errors: // Initializing Pg const { Client ...

Utilizing properties to transfer a reference object to a nested component

Is it safe to do the following in React: function Parent() { const myRef = useRef([1, 2, 3]); console.log("parent: " + myRef.current); return <Child myList={myRef.current} />; } function Child({ myList }) { const [currInt, setCurrInt] = useS ...

The Navbar's Toggle Icon Causes Automatic Window Resize

I implemented a mobile navigation bar using React and JS that slides in from the left when clicked. However, I encountered two issues: whenever I click on a menu button in the navbar or when my ad carousel moves, the window resizes for some reason. Additio ...

Troubleshooting a React Node.js Issue Related to API Integration

Recently, I started working on NodeJs and managed to create multiple APIs for my application. Everything was running smoothly until I encountered a strange issue - a new API that I added in the same file as the others is being called twice when accessed fr ...

Discovering the current time and start time of today in EST can be achieved by utilizing Moment.js

Need help with creating Start and End Time stamps using Moment.js in EST: Start Time should reflect the beginning of today End Time should show the current time. This is how I have implemented it using moment.js: var time = new Date(); var startTime=D ...

Sinon.js: How to create a mock for an object initialized with the new keyword

Here is the code that I am working with: var async = require('async'), util = require('util'); var Parse = require('parse/node'); function signup(userInfo, callback) { var username = userInfo.username, email ...

Activating two buttons in jquery will trigger this action

I am currently working on developing a filter button that will perform different actions based on which buttons are pressed. Pressing button1 will trigger one action, while pressing button2 will trigger another action. If button1 is pressed first, followe ...

What are some ways to design unique custom data grid toolbar elements?

I am having trouble syncing my custom toolbar buttons with the imported material data grid toolbar components. I would like them to match in style, specifically applying the material styles to my custom components. However, I have not been able to find a w ...

I am looking to transmit information to the controller using AJAX

ajax console.log(total);//10 console.log(number);//4 var form = { total:total, number:number } $.ajax({ url: 'items/cart/update', type: 'POST', data:form }); Spring MVC controller @ResponseBody @P ...

What is the best way to implement Media Queries in the Next.js application Router?

I am currently working with Next.js 13 and the App Router. Within my client component, I have implemented media queries in JavaScript to customize sidebar display for small and large screens. "use client"; export default function Feed() { co ...

What role does a promise play in rendering code asynchronous?

While we often use promises to avoid the dreaded function callback hell, a question remains: where exactly in the event loop does the promise code execute and is it truly asynchronous? Does the mere fact that the code is within a promise make it asynchron ...

Is it possible to configure the Eclipse Javascript formatter to comply with JSLint standards?

I'm having trouble setting up the Eclipse Javascript formatting options to avoid generating markup that JSLint complains about, particularly with whitespace settings when the "tolerate sloppy whitespace" option is not enabled on JSLint. Is it possible ...