Asterisk
Asterisk

Reputation: 3574

How to sort two tables located side by side so that changes in one are reflected in the other

Suppose I have two tables A and B and each one has only 1 column.

Each row in table A corresponds to each row in B, but I don't want them to be in one table.

A       B 
------  ----------
car     automobile
bike    train

When I sort A alphabetically I should get

A       B 
------  ----------
bike    train
car     automobile

Upvotes: 3

Views: 246

Answers (2)

Anurag
Anurag

Reputation: 141879

Since the items in table A have a one-to-one correspondence to the items in table B, it's better to use an object to represent this data. An array of these objects represents the entire dataset. Whenever a sort is needed, just sort this array, and repopulate the tables.

// first represents the item in table A
// second represents the item in table B
function Transporter(first, second) {
    this.first = first;
    this.second = second;
}

Then create a custom sort function that only compares the property first for sorting an array of Transporter objects.

function compare(a, b) {
    if(a.first < b.first) {
      return -1;
    }
    else if(a.first > b.first) {
      return 1;
    }
    return 0;
}

And a test run:

var transporters = [];
transporters.push(new Transporter("car", "automobile"));
transporters.push(new Transporter("bike", "train"));

console.log(transporters); // [0] => (car:automobile), [1] => (bike:train)
transporters.sort(compare);
console.log(transporters); // [0] => (bike:train), [1] => (car:automobile)

When the sort is done, update both tables.

Or, alternatively use any existing script or plugin. Here's one for jQuery: http://tablesorter.com/docs/

Upvotes: 1

James
James

Reputation: 111940

Surely, this is as simple as two calls, assuming a sufficient abstraction.

sortingModule.sort( document.getElementById('table-a') );
sortingModule.sort( document.getElementById('table-b') );

I think you need to give us more details. Have you written the sorting mechanism?

Upvotes: 1

Related Questions