phantom phantom - 6 months ago 15
jQuery Question

Create a table from an object jquery/javascript

I am trying to implement the following.

A user enters a sentence into a textbox following which a table is created. An example would be this.

Input:

"This is what I want to achieve"


Result:

enter image description here

Currently, based on the code I have there is an object that looks like this:

{t: ["this", "to"], i: ["is", "i"], w: ["what", "want"], a: ["achieve"]};


Below is the current code I have (also see jsfiddle here).

I am able to take the input string and create a table with a row which has the first letter of each word.

HTML

<textarea id="text-input" name="textarea" rows="5" cols="25">This is what I want to achieve</textarea>
<button class="calculate">Calculate</button>

<table>
<tbody>
<tr class="words-header"></tr>
</tbody>
</table>


Javascript

$(document).ready(function() {
$(".calculate").click(function() {
var result = {},
arr = [];
var array = $("#text-input").val().toLowerCase().split(" ");

for (var i = 0; i < array.length; i++) {
if (typeof result[array[i][0]] == 'undefined') {
result[array[i][0]] = [];
}
result[array[i][0]].push(arr[i]);
}
for (var key in result) {
$(".words-header").append("<td>" + key.toUpperCase() + "</td>");
}
});
});


I believe the final table should look like this if it helps:

<table>
<tr>
<td>A</td>
<td>I</td>
<td>T</td>
<td>W</td>
</tr>
<tr>
<td>achieve</td>
<td>is</td>
<td>this</td>
<td>what</td>
</tr>
<tr>
<td> </td>
<td>i</td>
<td>to</td>
<td>want</td>
</tr>
</table>

Answer

You can do it this way (Try it by clicking the Run code snippet button below):

var app = app || {};
(function() {
    "use strict";

    var result = [],
        arr = [];

    app.initialize = {
        init: function() {
            app.splitWords.init();
        }
    };

    app.splitWords = {
        init: function() {
            $(".calculate").click(function() {
                arr = $("#text-input").val().split(" ");
                app.createMultiArray.init(arr);
            });
        }
    };

    app.createMultiArray = {
        init: function(array) {
            for (var i = 0; i < array.length; i++) {
                var letter = array[i][0].toLowerCase();
                if (typeof result[letter] == 'undefined') {
                    result[letter] = [];
                }
                result[letter].push(array[i]);
            }
            // I added this method
            app.buildTable.init(result);
        }
    };

    app.buildTable = {
        init: function(result) {
            var headers  = Object.keys(result),
                max_rows = 0,
                rows_html = '';
            headers.sort();
            app.createHeaders.init(headers);
            // Determine how many rows you'll need
            for (var i = 0; i < headers.length; i++) {
                if(result[headers[i]].length > max_rows) { max_rows = result[headers[i]].length; }
            }
            // Loop "max_rows" times
            for (var i = 0; i < max_rows; i++) {
                rows_html += '<tr>';
                // Loop through all letters
                for(var j = 0; j < headers.length; j++) {
                  rows_html += '<td>';
                  if(i < result[headers[j]].length) {
                      rows_html += result[headers[j]][i];
                  }
                  rows_html += '</td>';
                }
                rows_html += '</tr>';
            }
            $(".words-header").after(rows_html);
        }
    };
  
    app.createHeaders = {
        init: function(headers) {
            for (var i = 0; i < headers.length; i++) {
                $(".words-header").append("<td>" + headers[i].toUpperCase() + "</td>");
            }
        }
    };

    app.docOnReady = {
        init: function() {
            app.initialize.init();
        }
    };

    $(document).ready(app.docOnReady.init);

})(jQuery);
#results-table table{ border-collapse: collapse; } #results-table td{ border: 1px solid #000; padding: .2em;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<textarea id="text-input" name="textarea" rows="5" cols="25">This is what I want to achieve</textarea>
<button class="calculate">Calculate</button>

<div id="results-table">
  <table>
    <tbody>
      <tr class="words-header"></tr>
    </tbody>
  </table>
</div>