0

In this example for Multi-dimensional sorting it uses this first column as the sort column

var shapes = [
    [5, "Pentagon"],
    [3, "Triangle"],
    [8, "Octagon"],
    [4, "Rectangle"]
    ];

shapes.sort(function(a, b)
{
    return a[0] - b[0];
});

I would like to edit this anonymous function so I could pass the column ordinal I want to sort on, otherwise I'm going to have to have different sort function for each column and it is going to get very messy very quickly. I've googled around but can find nothing suitable.

As a rough guess I no it does not work, but this is what I want:

shapes.sort(function(a, b, COL)
{
    return a[COL] - b[COL];
});

Where COL is new passed param. Thanks!

1
  • 2
    Woa! Lot of downvoting answers going on!? What is happening? Commented Jan 23, 2015 at 10:30

2 Answers 2

0

The .sort() function does not allow to pass your own parameter (apart from a and b) to it. What you can do instead is to declare your parameter outside of .sort() and call it inside of .sort().

Also, if you use use > for comparison inside of .sort(), it will sort those words too!

var shapes = [
  [5, "Pentagon"],
  [3, "Triangle"],
  [8, "Octagon"],
  [4, "Rectangle"]
];

var col = 1;

shapes.sort(function(a, b)
{
  return a[col] > b[col];
});

console.log(shapes);

Sign up to request clarification or add additional context in comments.

1 Comment

If you are downvoting, please have the courtesy to mention WHY.
-2

You may use carrying:

function sort_func (column, a, b)
{
    return a[column] - b[column];
}
shapes.sort(sort_func.bind(null, column))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.