IMPORTANT: If working with numerics, I recommend you parse your values to the correct type before comparisons for the most accurate results. For example, using "parseInt" or "parseFloat". This is especially important for floats, as you'll get bad results when sorting if they're represented as strings.
@@krichter9245 you probably need to sort it differently based on the type of column, here's what I did: if (column !== 1) { sortedRows = rows.sort((a, b) => { const aColText = a.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim(); const bColText = b.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim();
return aColPrice > bColPrice ? (1 * dirModifier) : (-1 * dirModifier); }) } so basically I chekced to see if it was the column with numbers in it and sort differently based on that. one month late reply idk how useful this will be to you but good luck!
So good, thank you. In my implentation, table are dynamically produced using AJAX calls. I linked the js at the top as if it were a CDN or something like that and it did not work. I solved it by adding the link to the js right after the script with the AJAX call, just in case someone else encounters a similar problem. Thanks again for this awesome tutorial.
Amazing!!! It helped a lot, It would be much cooler if the table heads add already the sorting icons and each time we clicked on the head cell the corresponding icon would turn to a different color, so people would know that the table is sortable. anyways 5 starts keep it up!!
Hello! I was wondering if you could tell me, how would you edit your table to only sort one column? I imagine it would be in headerCell function. Would you edit the tableElement variable? Or would it be in the document.querySelectorAll(".table-sortable th") part? Thank you so much if you could help me with this!
Very eloquent video, as usual. Just a quick question: instead of concatate .parentElement, would'nt be more effiicient to use .closes()? In that way, you don't have to previously be aware hay many levels there are from th to table. (and less code redundancy, maybe); Thanks for this videos, btw!
So cool. Thank you. I got it to work with my php table as well and it works almost perfect. Sorting names, no problem, sorting numbers its a little fiddly though.
@@michaelwang1524 I had this problem too and this sorted it, thank you! My first column is made up of strings and the rest numbers so I added an if statement to differentiate between your return code and the one used in the video.
Great code !! I managed to solve the problem with better sorting of numbers, and add some code that can detect if the table is with numbers or letters.
Hello, I'm using this code and it works very well. However, when I use it on paginated tables, it will only sort the rows found on the current page. I want it to sort all the rows. Please help.
great video for a complete .js noob like me even though it didn't work for me and I don't not finde the mistake I made, so I had to copy your script from code pen... at least I tried XD Im wondering how to put the table back in the original sequence as it was before sorting without reloading the site? the tables at wikipedia for example do have this 3 states for each column - asc, desc and back to original...
Instead of traversing DOM one by one like: const tableElement = headerCell.parentElement.parentElement.parentElement; It's easier just to use closest() method. const tableElement = headerCell.closest('.table');
Thanks for sharing this will help a lot for my current project , but there's a line of code that I cannot understand please see below: return aColText > bColText ? (1 * dirModifier) : (-1 * dirModifier); what does this code mean ? thanks !
It's using the ternary operator: developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator We want either -1 or 1, and the dirModifier flips number (-1 or 1) depending on if we are sorting ascending or descending
Thanks again for great video and code. I figured it out. I set the 'asc' parameter to 'false' in the sortTableByColumn function and also named the const dirModifier = asc ? from 1 : -1 to -1 : 1
I get error in declaring the constants, like: sortedRows is declared but it's value is never read. I'm all day on it trying to solve it. I'm using visual studio 2017. Help please anybody?
Why are you using such a convoluted and complex way of getting the index of each clicked 'TH', when you can just use the 'index' argument of forEach() instead? Instead of this: const headerIndex = Array.prototype.indexOf.call(headerCell.parentElement.children, headerCell), you can just pass 'index' argument, and then assign it to headerIndex.
IMPORTANT:
If working with numerics, I recommend you parse your values to the correct type before comparisons for the most accurate results. For example, using "parseInt" or "parseFloat".
This is especially important for floats, as you'll get bad results when sorting if they're represented as strings.
could you change it up in the Source Code that you linked? would really apreciate it because i can't make it work how it should.
Ok i made it work but now the name won't be sorted correctly..
@@krichter9245 you probably need to sort it differently based on the type of column, here's what I did:
if (column !== 1) {
sortedRows = rows.sort((a, b) => {
const aColText = a.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim();
const bColText = b.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim();
return aColText > bColText ? (1 * dirModifier) : (-1 * dirModifier);
})
}
else {
sortedRows = rows.sort((a, b) => {
const aColPrice = parseFloat(a.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim().replace('$', ''));
const bColPrice = parseFloat(b.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim().replace('$', ''));
return aColPrice > bColPrice ? (1 * dirModifier) : (-1 * dirModifier);
})
}if (column !== 1) {
sortedRows = rows.sort((a, b) => {
const aColText = a.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim();
const bColText = b.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim();
return aColText > bColText ? (1 * dirModifier) : (-1 * dirModifier);
})
}
else {
sortedRows = rows.sort((a, b) => {
const aColPrice = parseFloat(a.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim().replace('$', ''));
const bColPrice = parseFloat(b.querySelector(`td:nth-child(${ column + 1 })`).textContent.trim().replace('$', ''));
return aColPrice > bColPrice ? (1 * dirModifier) : (-1 * dirModifier);
})
}
so basically I chekced to see if it was the column with numbers in it and sort differently based on that.
one month late reply idk how useful this will be to you but good luck!
@@samuelhowell5962 Thanks Dude, Take care
@@samuelhowell5962 It was really useful to me. Thank you!!
Thanks bro. A big hug from Porto (Portugal).
Thanks so much for this.! Is there a way to turn off the sorting capacity for a specific column (e.g.: the last column)?
its easy when you do it, applied and it works, but wouldnt figure out myself. Thanks a lot. Will make use of it for my ajax loaded tables.
great job, thx for showing!
So good, thank you. In my implentation, table are dynamically produced using AJAX calls. I linked the js at the top as if it were a CDN or something like that and it did not work. I solved it by adding the link to the js right after the script with the AJAX call, just in case someone else encounters a similar problem. Thanks again for this awesome tutorial.
It works so beautifully! Thanks Man!
Amazing!!! It helped a lot, It would be much cooler if the table heads add already the sorting icons and each time we clicked on the head cell the corresponding icon would turn to a different color, so people would know that the table is sortable. anyways 5 starts keep it up!!
*had
*stars xDD
holy shit my english
Thank you for making a complex issue to me look easy!
Thank you it's the best lesson that I ever seen)))))
Cheers!!
Bro, you resolve my problem , thanks for that! new sub
Thank you for this video. Very well done!
Very helpful reference. Thank you!
how can i use this without click mean , when load the page it automatically sort for first column ???
thank you very much, the code is super functional.
Thanks man for this information. Keep it up
No worries mate!
Thanks mate! Keep it up!
Cheers mate!
I think there's a problem with case-sensitive entries, they seem to prioritize capitalized/upper-cased letters than lower-cased ones
thank >>>you can add toturial for multi filter table depend on html or javascript
Hello! I was wondering if you could tell me, how would you edit your table to only sort one column? I imagine it would be in headerCell function. Would you edit the tableElement variable? Or would it be in the document.querySelectorAll(".table-sortable th") part? Thank you so much if you could help me with this!
@dcode Why is that video part of the JavaScript Classes playlist?
Excellent mate. Thanks for sharing.
Thank you! This video helped me sort my table lol
Awesome video! I’m making a project and I want to do this but whit an input, so the client select the csv file and displays in the srcren
Very eloquent video, as usual. Just a quick question: instead of concatate .parentElement, would'nt be more effiicient to use .closes()? In that way, you don't have to previously be aware hay many levels there are from th to table. (and less code redundancy, maybe);
Thanks for this videos, btw!
Thanks for the amazing tutorial, helped a lot!
do I have a possibility not to sort the Rank? let the rank fix?
So cool. Thank you. I got it to work with my php table as well and it works almost perfect. Sorting names, no problem, sorting numbers its a little fiddly though.
hey idk if this helps you sort the numbers
const sortedRows = rows.sort((a, b) => {
const aColText = a.querySelector(`td:nth-child(${ column + 1})`).textContent.trim();
const bColText = b.querySelector(`td:nth-child(${ column + 1})`).textContent.trim();
const aNum = parseInt(aColText);
const bNum = parseInt(bColText);
return (aNum - bNum) > 0 ? (1 * dirModifier) : (-1 * dirModifier);
});
@@michaelwang1524 Thank you so much. That totally worked. Greatly appreciated.
@@TownleyVM You know what we should totally work together if ur also building a website so we can bounce ideas off of each other.
@@michaelwang1524 I had this problem too and this sorted it, thank you! My first column is made up of strings and the rest numbers so I added an if statement to differentiate between your return code and the one used in the video.
Great code !!
I managed to solve the problem with better sorting of numbers, and add some code that can detect if the table is with numbers or letters.
please share
This was very useful, thanks a lot!
Hello, I'm using this code and it works very well. However, when I use it on paginated tables, it will only sort the rows found on the current page. I want it to sort all the rows. Please help.
Awesome video! How do you make it sort selected values from a dropdown column? Thanks!!
Thank you for this video!
Awesome work, is it possible to filter on the name column?
Would you consider doing a follow-up video on how to do this if possible please?
great video for a complete .js noob like me even though it didn't work for me and I don't not finde the mistake I made, so I had to copy your script from code pen... at least I tried XD Im wondering how to put the table back in the original sequence as it was before sorting without reloading the site? the tables at wikipedia for example do have this 3 states for each column - asc, desc and back to original...
Awesome, thanks
Really amazing and thanks for making this
No problem!
you are awesome dude
Thanks! I'm tired of using CSS libraries
How to increase size of that sort arrow
Thanks fort this! But the code doesn't seem to work if the table is populated with AJAX?
Instead of traversing DOM one by one like:
const tableElement = headerCell.parentElement.parentElement.parentElement;
It's easier just to use closest() method.
const tableElement = headerCell.closest('.table');
That's a much better solution. I've been using it in my recent videos. Thanks 😀
thanks it works great
Hello, what if I want to work with table that requires calculations?
thanks ! very helpful
How can I do pagination?
Cheers mate 🍻
Do I have to change anything to make this work with flask? Mine isn't working. Nothing happens =(
Thanks for the tutorial. It's great. It Just helped me in my project
Great help and amazing explanation! The question is how can i do this beautiful sorting you did using DropDown menus and Select Tags?
Great video but Does this work on pagination?
Thank you so much! :)
You're welcome, glad it could help
how to sort table column based on dropdown option
Thanks for sharing this will help a lot for my current project , but there's a line of code that I cannot understand please see below:
return aColText > bColText ? (1 * dirModifier) : (-1 * dirModifier);
what does this code mean ? thanks !
It's using the ternary operator: developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
We want either -1 or 1, and the dirModifier flips number (-1 or 1) depending on if we are sorting ascending or descending
@@dcode-software thank you sir
Thanks for posting this tutorial, it is fantastic! What part o the code would I change to have the first column click present the descending order?
Thanks again for great video and code. I figured it out. I set the 'asc' parameter to 'false' in the sortTableByColumn function and also named the const dirModifier = asc ? from 1 : -1 to -1 : 1
how to integrate this with mysql?
if i don't want to sort all the columns, what should i change please?
Did you got anything for this?
I get error in declaring the constants, like: sortedRows is declared but it's value is never read. I'm all day on it trying to solve it. I'm using visual studio 2017. Help please anybody?
Clicked subs and love you
can i also sort certain categories(dates dont function)
did u get the solution?
when i try inspect its working but its not sorting. need help please
Same problem
You are awesomeeeeeeeeeeeeeee!!!! thx
How can you keep the ranking order unchanged ?
You could make use of something like Local Storage or Session Storage
I made it work with a forEach on every row to keep the index before adding to the empty table...thank you for the quick reply:D
Can you do this with Vue? would be awesome
Thank you!!! :-D
Great tutorial thanks!!
Can you also do a tutorial on pagination
not working in paginations
If numbers are more than 10 it sorting 1 10 11 2 3 4... or 9...3 2 11 10 1 it's ok if writing 01 02 03... :)
everything works for me but not the CSS i dont know why anyone having issue applying css arrows doesnot appear?
Sort by numbers only
const sortedRows = rows.sort((a, b) => {
const aColText = a.querySelector(`td:nth-child(${ column + 1})`).textContent.trim();
const bColText = b.querySelector(`td:nth-child(${ column + 1})`).textContent.trim();
const aNum = parseInt(aColText);
const bNum = parseInt(bColText);
return (aNum - bNum) > 0 ? (1 * dirModifier) : (-1 * dirModifier);
});
I followed the video and my sorting doesnt work :(
Great
Bro, please share code
It's there in the description
🙏🏽🙏🏽🙏🏽
Why are you using such a convoluted and complex way of getting the index of each clicked 'TH', when you can just use the 'index' argument of forEach() instead? Instead of this: const headerIndex = Array.prototype.indexOf.call(headerCell.parentElement.children, headerCell), you can just pass 'index' argument, and then assign it to headerIndex.
Hi,
Can you share full code please
Thank you so very much. For this beautiful tutorial :)
How to pagination with it?