• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Sorting in JavaScript

Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I have a table, which is to be made sortable. When the user clicks on first column header it should sort on the first column i.e. Order by first column
, and then under the first column data, order the data in second column......and so on. User can click on any of the columns so the order by will also change accordingly.

as an example.

if the columns available are:

Project name, Employee name.

If there are two projects which starts from letter 'k', then after sorting on projects column, it should sort on employee name column for those two projects.

Is it possible to do this with javascript.
Could somebody provide me with good links?
Posts: 15385
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is the mess I always wanted to get into with my table, but I never got around to it since I am working on my book.

I have not seen it anywhere online.
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Deepak
This can be done using javascript. You can follow this approach

1)Use a constructor to store all the column values. For example

function person(firstName, lastName, age)
this.FirstName = firstName;
this.LastName = lastName;
this.Age = parseInt(parseFloat(age));
2)Store all the objects in an array
e.g. people[people.length++] = new person("amol", "sonawane", 22);
Here values will come from your table columns

3)Write the appropriate sorting function
e.g. function sortByFirstName(a, b)
var x = a.FirstName.toLowerCase();
var y = b.FirstName.toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
4)Use the inbuilt sort function of javascript arrays
e.g people.sort(sortByFirstName);
5) Populate your html table dynamically using this sorted array

Hope this answers your problem
- amol
It runs on an internal combustion engine. This ad does not:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
    Bookmark Topic Watch Topic
  • New Topic