Breaking down a JavaScript string into two separate arrays

Imagine you have a string formatted like this: "Applejack=A.J.+Applecar,Lemon+Vodka=AlfieCocktail+ Sunset + SexOnTheBeach"

Your task is to write Javascript code using .split() to parse long strings (up to 100000 characters) and separate them into two arrays, with one containing the keys and the other containing the values. The output should be structured as follows:

key = ["Applejack", "Lemon+Vodka"]

values = ["A.J+Applecar","AlfieCocktail+Sunset+SexOnTheBeach"]

Answer №1

splitKey = string.split(',').map(x=>x.split("=")[0])
splitValues = string.split(',').map(x=>x.split("=")[1])

Answer №2

One way to achieve this is by following the code snippet below:

let dataString = "Applejack=A.J.+Applecar,Lemon+Vodka=AlfieCocktail+ Sunset + SexOnTheBeach";
let firstSplit = dataString.split(',');
let keysArray = [];
let valuesArray = [];
for(let j = 0; j < firstSplit.length; j++){
  let secondarySplit = firstSplit[j].split('=');
  keysArray.push(secondarySplit[0]);
  valuesArray.push(secondarySplit[1]);
}
console.log(keysArray);
console.log(valuesArray);

Answer №3

If you want to achieve this task, follow these steps:

let example = "Strawberry=Stacy+Banana=Mandy,Blueberry=Bob+Pineapple=Perry";
let items = example.split(','), categories = [], names = [];
items.forEach(item => {
    const [category,name] = item.split('=');
    categories.push(category);
    names.push(name);
})

console.log(categories,names);

Answer №4

A convenient method is to combine map with reduce for this task.

const str =
  "Banana=B.+BananaSplit,Strawberry+Milkshake=StrawShake+BlissfulBerry";

const [fruits, desserts] = str
  .split(",")
  .map((item) => item.split("="))
  .reduce(
    (acc, item) => [acc[0].concat(item[0]), acc[1].concat(item[1])],
    [[], []]
  );

console.log(fruits, desserts);

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

Adding a three-dimensional perspective to an HTML5 canvas without utilizing CSS3 or WebGL

Here is a canvas I am working with: http://jsbin.com/soserubafe Here is the JavaScript code associated with it: var canvas=document.getElementById("canvas"); var ctx=canvas.getContext("2d"); var w = canvas.width; var h = canvas.height; var cw=canvas. ...

Adding code containing various Google Maps elements in a fresh browser window using JavaScript

I've encountered an issue while trying to create a new page with a Google map and title based on the button clicked. Interestingly, when I copy/paste the HTML in the "newhtml" variable into an actual HTML file, it works perfectly fine. However, it doe ...

Using tsc with skipLibCheck flag will still perform checks on the node_modules directory

When I run the CLI command npx tsc --noEmit --skipLibCheck, I still encounter errors: node_modules/@types/node/util.d.ts:1631:41 - error TS1005: '(' expected. 1631 keys(): IterableIterator<string>; ...

Error encountered while utilizing JSON data in Ionic 2

Can someone help me with avoiding errors in TypeScript when filtering a specific variable in JSON data? Here is an example of part of my JSON data: Containing multimedia details: "per_facet": [], "geo_facet": [], "multimedia": [ { "url": "https://stat ...

Exploring the functionality of closing a modal in Karma-Jasmine testing

THE ISSUE AT HAND: In my Angular / Ionic app, I am currently in the process of testing a modal to ensure it is functioning correctly. While I have successfully tested that the modal opens as expected, I am facing difficulties in testing the proper closin ...

Trouble with video element and css not updating as expected based on conditions

I'm currently developing a video gallery featuring multiple videos that play sequentially. My goal is to eliminate the play button once it's clicked and display controls instead. I've attempted to use useRef and useState within useEffect, bu ...

Guide to utilizing nested map functions in JavaScript to retrieve specific elements

I have two arrays: one is a simple array, and the other is an array of objects. Here are the arrays:- arr1=["aadhar", "address", "email", "mobile", "name", "pancard", "voterid"]; arr2=[ { "id": 21, "name": "johndoe", " ...

Customizing Drop Down Button in React Material-UI with Conditions

Trying to figure out how to dynamically populate the second MUI dropdown based on the selection from the first dropdown. Currently, I have both dropdown lists hardcoded. const [queryType, setqueryType] = React.useState(''); const [subCategory, se ...

Display an image with HTML

My current project involves creating a chrome extension that will display a box over an image when hovered, while also zooming the image to 1.5 times its original size. In my research, I came across a similar example. .zoomin img { height: 200px; wi ...

Tips for making an input field that overlays text

I am currently working on a project that involves creating multiple cards using Bootstrap. Each card consists of a header, body, and footer. When a card is clicked on, I want an input field to appear in the header, footer, and body sections, overlaying the ...

Utilize Node.js v16 for the execution of chaincode operations

Currently, I am executing JavaScript/TypeScript chaincode from fabric-samples (asset-transfer-basic/chaincode-javascript) and my requirement is to switch the Node.js version from 12 to 16. I suspect that the hyperledger/fabric-nodeenv image is specifying ...

Is there a way to efficiently identify and decrease the frequency of a specific value within an array?

Below is an array structure I am working with: Array ( [0] => Array ( [name] => test [...] => ... ) [1] => Array ( [name] => wine [...] => ... ) ...

Enhance the Facebook Login popup with personalized settings

When a user clicks, a popup is triggered: FB.login(function () { // My CallBack }, { scope: 'email,user_birthday,user_location,user_hometown' }); This generates a Facebook login link with multiple parameters. I desire to inc ...

Sending an Ajax request to C# code

UPDATE After some research, I discovered what seems to be the "correct way" to handle the issue by using a combination of JSON.stringify and creating a model, as explained in this thread. I still can't figure out why the original approach didn't ...

Converting an array of strings into a JSON object using JavaScript

Below is an array that needs to be transformed into a JSON object: data = [ "Id = 2", "time = 10:59", "Topic = xxxxxxxxxxxxxxxx", "GUEST3", "Role = GS", "Infos = Connecticut", "GUEST4", "Role = HS", "Infos = Delaware", ...

How can the camera's yaw be accurately determined using THREE.js techniques?

Is there a way to calculate the 2D representation of an object's rotation (yaw) in a 3D scene using built-in methods in THREE.js? While I currently have this functionality working with the help of the solution provided at How to derive "standard ...

Mastering the art of using wildcards in CSS can help you harness the power of recognizing attributes

I am facing a situation where I have an HTML table with numerous cells, some of which are assigned classes like hov1, hov2, ..., hov42, ..., all the way up to hov920. This is a compact table where the darker green cells (hov1) change when hovered over whi ...

What could be causing the undefined value of $routeParams?

I've encountered an issue while attempting to utilize a service for managing an http request: angular .module('app') .factory('stats', function($http){ return { getStats: function(path) { ...

I crafted this dropdown menu, but for some reason, the selections aren't registering when clicked. Below is the code I used. Any assistance would be greatly appreciated!

Hi there, I need some help with getting my code to run properly. I've created a dropdown box using HTML and CSS, but it seems like there's an issue with the JavaScript portion as the options are not being selected. I've included a code snipp ...

Leveraging the power of Notepad++

When I attempt to use Notepad++ for Javascript, it isn't functioning as expected. Instead of displaying the proper outcome on the web page, all I see is a jumbled mess. Currently, I am using version 6.6.7 of Notepad++. Here's my process: Typ ...