Working with multiple arrays after splitting (jQuery)

jquery split string to array
jquery split array
javascript split regex
javascript split string by comma
javascript split string at index
jquery split string to array foreach
jquery split array by comma
javascript array

I am trying to create a web page that takes data from a CVS file and creates a custom for each row of content in the CSV file. I used jQuery to import CSV file and split the data it into an array:

promise = $.ajax({
    type:"GET",
    dataType:"text",
    url:"data.csv",
    cache:false
});

promise.done(function(data){

    //Parse CSV File
    //split on new line
    var dataArr = data.split("\n");
    console.log(dataArr);

Then I am using $.each to split each line into an array.

    //for each line in array
    $.each(dataArr,function(){
         var valArr = this.split(",");

screenshot of arrays

After that, I would like to take each created array and use it for creating my custom element. However, I can't figure out how to access each created array individually. If I access first item in the array by using valArr[0], I get results for the entire column A (instead of row 1, column A) in my CSV file. I'm new to Javascript, so I'm completely stuck here. Please point me in the right direction.

Thank you!

Update: added the HTML code I am using to insert the data from each row into.

<!doctype html>
<html lang="en">

<head>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>

<body>
    <!--Content start -->
    <div class="container-fluid">
        <div class="row">

            <!--Catalog content start  -->
            <div class="col">
                <div class="row allMyContent">

                    <!-- Card start -->

                    <div class='card mb-4 box-shadow col-5 ml-4'>
                        <div class="card-header" style="background-color: #fff;">
                            <!-- Link 1, 2, 3 etc go here (id #contentLink) -->
                            <a href="#" class="float-right ml-3" id="copyLink" id="contentLink">Link 1</a>
                            <!-- Course 1, 2, 3 etc go here (id #contentTitle) -->
                            <h5 class="my-0 font-weight-normal mr-5" id="contentTitle">Course 1</h5>
                        </div>
                        <div class="card-body">
                            <div>
                                <!-- Time and type go here (id #contentLength and #contentType) -->
                                <p><span class="mr-2" id='contentType'>Type 1</span> | <span class="ml-2"><span id='contentLength'></span> 20 min</span>
                                </p>
                            </div>
                            <div>
                                <!-- Description goes here (id #contentDescription) -->
                                <p id='contentDescription'>Description 1</p>
                            </div>
                        </div>
                        <div class="card-footer row" style="font-size: 0.85em;">
                            <!-- Audience, dates goe here (id #contentAudience #date1 #date2) -->
                            <small class="col" id='contentAudience'>Audience: HR</small>
                            <small class="col" id='date1'>Created: Jul-17</small>
                            <small class="col" id='date2'>Updated: Dec-17</small>
                        </div>
                    </div>
                    <!-- Card end -->

                </div>
            </div>
        </div>
    </div>
    </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
    <script src="app.js"></script>
</body>

</html>

Split() method to create array by breaking string using delimiterin in , Creating array by breaking strings using delimiters in split function. To return element from an array with starting and ending positions · Two Dimensional Array​: Adding and displaying elements For this we will use split() method which works on a string and create array out of it. After using split we are creating an array. jQuery Split. JQuery’s library contains the function split() that is utilized to separate a string into an array. One main parameter you need to pass is the separator. The separator can be a hyphen, comma or a space. Split (”): when you pass an empty string into the split method, it will then split every character in an array.

if valArr[0] contains whole A column why not iterate over it like this:

for(var column = 0; column < valArr.length; column++){
    var currentColumn = valArr[column];
    for(var item = 0; item < currentColumn.length; item++){
       console.log(currentColumn[item]);
    }
}

code above will iterate every column and over every item in every column, if you want to save whole row in variable you can do it like this:

function getRow(varArr, id){
    var retval = [];
    for(var column = 0; column < valArr.length; column++){
        var currentColumn = valArr[column];
        retval.push(currentColumn[id]); //add some checking if id is really present in this array
    }
    return retval;
}

code above will return something like this: [column_A_item_with_id, column_B_item_with_id, column_C_item_with_id, ...]

Split array value and assign to each variable, Hi,. If there are multiple items in the array, how to loop through it and then split. example: Test  const elementText = document.getElementById('TheData').innerText; const numericList = Array.from(elementText.split(',')).map(item => Number(item)); For more information: 1) getElementById: "The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

After modifying the code suggested by Roko and spending a bunch of time trying to figure out why it's not working, I realized I wasn't building the HTMl correctly. Here is the final result.

const data = `Course A,Link 1,Type1,20,Description 1,HR,Jul-17,Dec-17
Course B,Link 2,Type1,30,Description 2,HR,Oct-17,Dec-18
Course C,Link 3,Type2,60,Description 3,HR,Nov-17,Dec-19`;

const dataArr = data.split("\n");

        //Parse CSV File
        //split on new line
        const lines = data.split("\n");


        let HTML = '';

        //for each line in array
        lines.forEach(function(line, i) {
            var contentCards = line.split(",");
            HTML += '<div class="card mb-4 box-shadow col-5 ml-4">';
            HTML += '<div class="card-header">'
            HTML += '<h5 class="my-0 font-weight-normal mr-5" style="color: #ff8f00;">'
            HTML += '<a href="'
            HTML += contentCards[1];
            HTML += '" class="float-right ml-3" id="copyLink" style="color: #00a4b4; font-size: 1.2rem;"><i class="fas fa-external-link-square-alt"></i></a>'
            HTML += '<a href="'
            HTML += contentCards[1];
            HTML += '"class="float-right" style="color: #00a4b4; font-size: 1.2rem;"><i class="fas fa-link"></i></a>'
            HTML += contentCards[0];
            HTML += '</h5>'
            HTML += '</div>'
            HTML += '<div class="card-body">'
            HTML += '<div>'
            HTML += '<div class="card-body">'
            HTML += '<p><span class="mr-2">'
            HTML += '  <p><span class="mr-2 contentType">'
            HTML += contentCards[2];
            HTML += '</span>|<span class="ml-2"><i class="far fa-clock"></i ><span>'
            HTML += contentCards[3];
            HTML += ' min</span >'
            HTML += '</p>'
            HTML += '</div>'
            HTML += '<p>'
            HTML += contentCards[4];
            HTML += '</p>'
            HTML += '</div>'
            HTML += '<div class = "card-footer row" style = "font-size: 0.85em;" >'
            HTML += '</div>'
            HTML += '</p>'
            HTML += '</div>'
            HTML += '</div>'

            document.getElementById("courses").innerHTML = HTML;

        });
        console.log(HTML);
<head>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>
<div id="courses">

</div>

JavaScript, How to pass an array as a function parameter in JavaScript ? Difference between node.js require and ES6 import and export · How to Create Dark/Light Mode for Website using JavaScript/jQuery? Given a statement which contains the string and separators, the task is to split the All the items after limit are discarded. Creating arrays by using split method in a string We have seen how to create string using elements of an array. Now we will see how to create an array from a string by using some delimiter. For this we will use split() method which works on a string and create array out of it. This is one of the method used to create an array.

JavaScript, C · C++ · Java · Python · C# · Javascript · JQuery · SQL · PHP · Scala · Perl str.​split() function is used to split the given string into array of strings by separating it This function returns an array of strings that is formed after splitting the given string JavaScript | Split a string with multiple separators · JavaScript | Symbol.​split  As after your update it is actually that you are splitting each index inside the ingredients array on a regex i.e /[:;,.]/ and the resulting indexes of the array can vary and for all those arrays after splitting you want to be merged into a single array so you need to use Array.prototype.concat() see a demo below

JavaScript String split() Method, If omitted, the entire string will be returned (an array with only one item). limit, Optional. An integer that specifies the number of splits, items after the split limit will  Optional. Specifies the character, or the regular expression, to use for splitting the string. If omitted, the entire string will be returned (an array with only one item) limit: Optional. An integer that specifies the number of splits, items after the split limit will not be included in the array

Let's clear up the confusion around the slice( ), splice( ), & split , Let's clear up the confusion around the slice( ), splice( ), & split( ) Firstly, you need to understand how JavaScript arrays work. Like in other programming languages, we use arrays to store multiple data in JS. After 1st call:. jQuery splice() method requires two parameters, the first parameter is the index of the item from where to start splitting and second parameter is the number of items to be removed from the array after the specified index.

Comments
  • Roko, this is super helpful! I'm trying to do more than just a table with this data though. I am trying to create a boostrap card and need to pul my data into specific place in HTML. I attached my html and also screenshot. Any suggestion how I can do it?
  • Roko - I added the html code into my original post.
  • Thank you for suggestions and your help! I tried plugging the code and doesn't seems to work. What I am trying to do is to simply select Array 1 and then select item 1 (then 2,3,4 etc) in that Array and plug that item in the array into my div. However, after split, I get three arrays assigned to one variable (see screenshot in the original post). I am not sure how to split the array into separate array now so I can access each value.
  • are those arrays correct or not? I mean, is it correct that field one has to contain 'course a' and field next to it has to contain 'link 1' etc?
  • Yes, correct. Each array individually has exactly the data I need. However, I can't figure out how to access each item individually (i.e. course 1, course 2, course 3 - these will be heading for each <div>,). When I try to access them individually, I get all first items in the array together (i.e. Course 1 Course 2 Course 3). Hope it makes sense.
  • so when you get all items in one array together what's the issue? can't you just acces them like result[0] result[1] etc?
  • No, unfortunately, I can't. I added the html where I am trying to insert the results into the original post. I am trying to take a specific item into the new split array and insert it in the specific place in my boostrap card.
  • No, don't use innerHTML inside a loop! See how console.log(HTML) returns properly outside of the loop? Use it there! Also, you could make use of tempalte literals: jsbin.com/qoqecuh/1/edit?html,css,js,output
  • Wow, this is much easier solution. Lot it. Thank you very much, Roko!
  • Can you post your code as a comment so I can vote it as a correct answer?
  • I would like to learn more about the syntax you used to select the item in the array ${contentCards[5]}. I tried to Google it but didn't see anything. Is it jQuery or pure JavaScript?
  • it's ES6's Template Literals. Just like strings but more powerful since it allows multiline templateing and simple variables inclusion using the ${} wrapper. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…