0

I have an array of arrays, each array within the array is set up like this

[1, firstname, lastname, 22]

I have a total of 12 of these, I am trying to sort the arrays by the 4th element of each array in descending order but nothing I have tried has worked, namely I have been trying to do array.sort with a comparison function and having look at the 4th element in each array but cant get it to work. Here is what I currently have:

function sortArray (a, b){
    return a-b;
}

for (var k = 0; k<employeeArray.length; k++){
    var j = k-1;
    employeeArray.sort(sortArray([k][3],[j][3]));
}

What I was expecting was for the function to sort the arrays by the 4th element but it keeps throwing up Uncaught Type errors.

Bahman Parsa Manesh
  • 2,314
  • 3
  • 16
  • 32
Ryan
  • 321
  • 2
  • 9
  • 1
    You're passing a *numeric value* to `sort`. You need to pass a *function* which returns such a numeric value. Something like `employeeArray.sort((a, b) => b[3] - a[3])` – Scott Sauyet Nov 30 '18 at 17:21

1 Answers1

2

I would recommend reading up on how sort works.


The .sort method handles the sorting. You do not need a for-loop.

Instead, you need to make your function sort two entries properly:

function sortTwoArrays(a, b){
    return a[3] - b[3];
}

Now you can just pass this as the parameter to the .sort method of your employeeArray:

employeeArray.sort(sortTwoArrays);

which will modify the array.

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54