Hello, I'm a beginner and I need help sorting the table rows in the following table. I also want to attach an onclick listener to the header after it is displayed.
ID | Name | Inventory Volume |
---|---|---|
1 | Rachel | Data is not enough |
2 | Ross | 100 |
3 | Monica | 1 |
4 | Connor | Data is not enough |
5 | Dustin | -5 |
I would like to sort this table with the words at the end in descending order.
ID | Name | Inventory Volume |
---|---|---|
2 | Ross | 100 |
3 | Monica | 10 |
5 | Dustin | -5 |
1 | Rachel | Data is not enough |
4 | Connor | Data is not enough |
In addition, I'd like the other columns to be sorted as well and have the function to sort them too.
I tried a solution but it only works for one column. Here is the link to my code: https://jsfiddle.net/7wnke5q2/
function sortData(data, method) {
let lessData = 'Data Not Enough'
let lastItems = []
let sortedList;
if (method == 'descending') {
sortedList = data.sort((a, b) => {
return a - b
})
} else if (method == 'ascending') {
sortedList = data.sort((a, b) => {
return b - a
})
}
for (let i = 0; i < sortedList.length; i++) {
if (sortedList[i] == lessData) {
let item = sortedList[i]
sortedList.splice(i, 1)
sortedList.push(item)
}
}
sortedList = sortedList.concat(lastItems)
return sortedList
}
I would really appreciate your help. Thank you!