• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Sorting in JavaScript

 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

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?
 
author
Posts: 15385
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
regards
- amol
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic