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.

1
  • 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]) Commented Nov 30, 2018 at 17:21

1 Answer 1

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.

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

2 Comments

Thank you! This is exactly what I was trying to do!
@Ryan Please accept then!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.