So for example I have a table that is displayed like this.
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<h2>HTML Table</h2>
<table>
<tr>
<th>ID</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>6</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>5</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>4</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>3</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
<tr>
<td>1</td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<td>2</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
</table>
So this data is not save on my database, but I have save their actual count, so whenever I'm gonna edit they will just be rumble in my view, and my goal is to arrange them first based on their count.
var count = [1,2,3,4,5,6];
so with this array, assume that this is their arrangement. My question is how or is it possible to arrange them base on my count variable by using the ID column?
Yes, it's possible:
const sort = (rows, sort) => sort.map(e => rows.find(({ id }) => id == e))
const getRowId = (row) => +jQuery(jQuery(row).find('td')[0]).text() // 0 is the first column
const getSortObj = (row) => ({ id: getRowId(row), row })
const setDirectionText = (directionSpan) => (direction) => directionSpan.text(direction)
jQuery(document).ready(function($) {
let sortByArr = [1, 2, 3, 4, 5, 6]
let direction = "ASC"
const directionSpan = setDirectionText($("#direction"))
directionSpan(direction)
$('#btn-sort').on('click', function() {
const $rows = $('#table tbody tr')
const sortedRows = sort($.map($rows, getSortObj), sortByArr).map(({ row }) => row)
$('#table tbody').html(sortedRows)
sortByArr = sortByArr.reverse()
direction = direction === "ASC" ? "DESC" : "ASC"
directionSpan(direction)
})
})
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>HTML Table</h2>
<button id="btn-sort">SORT TABLE <span id="direction"></span></button>
<br />
<br />
<table id="table">
<thead>
<tr>
<th>ID</th>
<th>Contact</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>6</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>5</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>4</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>3</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
<tr>
<td>1</td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<td>2</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
</tbody>
</table>
This snippet does a bit more than you asked for: it can sort in ascending and descending order - toggled after each sorting.