Transforming a single-dimensional array of strings into a two-dimensional array

Being relatively new to this, I'll dive straight into the problem I need help with:

I need to transform this: "cat@dog%arm@hand%tree@apple..."

into something like this:

cat | dog
arm | hand
tree| apple
..etc

While isolating the strings is not an issue, manipulating them into a 2D array or two columns in a spreadsheet has proven to be challenging.

Here's one approach that I've tried: `

function key_abb(input) {
  if(input.map) { 
    return input.map(key_abb);
  }else {
    var temp = input.toString();
    temp = temp.replace("abbreviated-name=", "");
    temp = temp.replace("name=", "");
    return temp;
  }
}`

input represents data formatted in the following way:

|abbreviated-name="cat"  name="dog"  |
|abbreviated-name="arm"  name="hand" |...

Despite attempting this solution, I'm still only getting both strings within the same column. The only achievement so far is removing the extra text. I'm unsure how to create the desired output array. Appreciate any assistance on this matter!

Answer №1

Check this out:

string = 'sun@moon%earth@mars';
data_list = string.split('%');

for (var i = 0; i < data_list.length; i++) {
    data_list[i] = data_list[i].split('@');
}
    
console.log(data_list);

The outcome will be:

[
    ["sun", "moon"],
    ["earth", "mars"]
]

Answer №2

Consider this alternative approach that utilizes the Array.map() method:

var message = 'sky@sea%river@mountain%sun@moon';
var data = message.split('%').map(function(part) {
  return part.split('@');
});
    
console.log(data);

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

Feeling overwhelmed by JavaScript jQuery errors when making an Ajax request?

I am facing an issue with two buttons on my webpage. One button triggers a table refresh using an ajax php request, while the other button is set to automatically refresh the table every 10 seconds. However, when attempting to access the document, I am enc ...

What is the best way to enable users to include additional choice information?

I have a dropdown list where the user can select an option, and based on their selection, specific form inputs are displayed. Here is the HTML code: <select id="relative" name="relative"> <option>Choose a relative</option> <o ...

Footer flickers while changing routes

There seems to be a glitch where the footer briefly flashes or collapses when switching routes, specifically if the page is scrolled down to the middle. If at the top of the page, the transition works smoothly. This issue becomes more apparent on high refr ...

What is the process for comparing a jQuery .html() variable with HTML generated by Ruby on Rails?

My current challenge involves comparing two variables, newhtml and oldhtml. The old html is obtained using: var oldhtml = $('#pop').html(); The new html is obtained using: var newhtml = ("<%= escape_javascript render(:file => 'shar ...

Extract all content from a Div following a hyphen and stop at the first character

I'm currently attempting to create a function that can locate specific text within a div and then display all the text that comes after the '-' character in the console. There may be instances where there are spaces or tabs following the &ap ...

Angular directive has issues with $compile functionality

This Angular directive automatically appends a new HTML item to the page every time my model changes: app.directive('helloWorld', function($compile) { return { restrict: 'AE', replace: true, scope:{ ...

What is the best way to utilize a variable retrieved from a mysql connection in NodeJS within an asynchronous function?

My current project involves scraping a website using Puppeteer. I am aiming to extract the date of the last post from my database and compare it with the dates obtained during the scrape. This way, I can determine if a post is already present in the databa ...

Is there a way in Node.js to showcase a list of choices using console log and prompt the user to input an option from the list displayed through console log?

Is there a way to use Node.js to show a list of options through the console log and prompt the user to input an option from the list via console log? Expected behavior user@desktop:~$ node test.js Option 1 Option 2 Option 3 Select an option to proceed: ...

Are there any alternatives to Google Charts for creating charts?

There is a restriction of only 2k queries per month, which I find insufficient. Are there any alternative classes, plugins, or tools that can be used to generate charts similar to those created by Google Charts? Thank you. ...

I am interested in invoking a function from a different component

I am facing an issue with my component AddPost.js where I am trying to use a method from machine.js. However, when I attempt to import AddPost into the machine.js file, it throws an error: Possible Unhandled Promise Rejection (id: 0): ReferenceError: addIn ...

Is there a way to refresh an item in an Express JS router automatically after a set period of time?

Is there a way to automatically update a mongoose schema through a post request after a certain period of time? I have a task that requires changing the boolean value from "livestream: false" to "livestream: true" within an hour or at a specified time. An ...

Utilizing external JSON data in JavaScript for retrieval

Is there a way to retrieve the value of categories.name_category in JavaScript? The AJAX call to the REST API is functioning correctly: https://i.sstatic.net/WJzoL.png I attempted to access it like this, but unfortunately it did not work as expected: ht ...

Automatically populating additional fields in JavaScript/React by taking information from the initial field

1. I am working with an array called "listOfPaysIndexes", which contains 12 indexes. My goal is to use this array to iterate through and display 12 DateInput fields. 2. Each of these fields can be clicked on to select a date. 3. Once a date is chosen in ...

Struggling to modify a variable within an Angular service using AJAX response data and then implementing it for filtering purposes

I've been implementing the code mentioned in this blog post about internationalization with AngularJS, but I'm encountering an issue. ... I want to fetch the "tables" variable from an AJAX request response using "$http get", but for some reason ...

Prevent data loss on webpage refresh by using Angular's local storage feature

As a beginner in Angular, I am exploring ways to retain user input and interactions on my webpage even after a refresh. After some research, I came across using local storage as a viable solution. A different answer suggested utilizing the following code s ...

In jQuery, there seems to be an issue where the click event is not functioning properly on an element that has been

I am using jQuery to append items, but I am having trouble binding events to the appended items. My appending code looks like this: var item = '<div id="'+newInputId+'" class="col-md-9" style="padding-right: 0px; ...

Preventing CSRF Attacks in an HTML Application with Laravel Route Protection

Currently, I am facing a challenge while developing an app with the PhoneGap API as it interferes with Laravel's 'View' property. Additionally, another issue arises as the index file must be in .html format, leaving me unsure of how to enha ...

What is the proper way to effectively update my array of Strings?

public static String[][] potentialOutcomes(Scanner fileScan, int weaponNumber) { int outcomeCount = (int)Math.pow(weaponNumber, 2); String[][] outcomes = new String[outcomeCount][outcomeCount]; String line = fileScan.nextLine(); ...

It is more beneficial to utilize jQuery instead of directly accessing form element values using document.formname

Just a quick question. Currently, I am working on some JavaScript for pre or frontend validation. I have a question about which line of code is more effective. I usually use this method: document.formname.forminput.value Instead of: $(& ...

Steps to keep a ByteArray unchanged in Kotlin

Is it possible to create an unmodifiable ByteArray in Kotlin? Similar to how we can create unmodifiable lists with Collections.unmodifiableList(byteList) ...