I have a problem sorting a table. 

My table HTML is this:

```
<table>
<tr>
  <td>3</td>
  <td>1</td>
</tr>
<tr>
  <td>2</td>
  <td>4</td>
</tr>
</table>

```

And I want it to look like this:

```
<table>
<tr>
  <td>1</td>
  <td>2</td>
</tr>
<tr>
  <td>3</td>
  <td>4</td>
</tr>
</table>

```

Here is my current sorting code:

```js
var rows = $('tr');

rows.eq(0).find('td').sort(function(a, b) {
  return $.text([a]) > $.text([b]) ? 1 : -1;
}).each(function(newIndex) {
  var originalIndex = $(this).index();
  rows.each(function() {
var td = $(this).find('td');
if (originalIndex !== newIndex)
  td.eq(originalIndex).insertAfter(td.eq(newIndex));
});
  });
```

```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table>
  <tr>
    <td>3</td>
    <td>1</td>
  </tr>
  <tr>
    <td>2</td>
    <td>4</td>
  </tr>
</table>
```

The code only sorts by separate rows. I can't use any plugins and I need to do this with jquery or javascript. Can anyone suggestion how to make it work?
['https://Stackoverflow.com/questions/40447377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7121533/']
It's simple.

1. Store all the numbers from `td` in an array.
2. Sort the array.
3. Modify the `td`s according to array.

Here's how you'd do it in JS:

```
var tds= [].slice.call(document.getElementsByTagName("td")); //Find <td> and store in array
var tdsa=tds.map(function (a) {return Number(a.innerHTML);}); //Take the innerHTMLs
tdsa.sort(); //Sort it
tds.forEach(function(a,i) {a.innerHTML=tdsa[i]}); //Modify <td>'s innerHTML

```
Try this - method:

* get the items of the table into an array
* sort the array
* rebuild the rows

```js
var columnCount = 2;
var items = [];
$('td').each(function (idx, obj) {
  items.push(obj.innerHTML);
});
items.sort();
$('table tr').remove();

for(var i=0; i<items.length; i+=2) {
  var row = '<tr>';
  for(var j=0; j<columnCount; j++) {
    row += '<td>' + items[i+j] + '</td>';
  };
  row += '</tr>';
  $('table').append(row);
};
```

```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table>
<tr>
  <td>3</td>
  <td>1</td>
</tr>
<tr>
  <td>2</td>
  <td>4</td>
</tr>
</table>
```