MZ Sorting an array of objects not working?

Hello again! I seem to be coming back here more and more with this latest project.

I'm trying to sort an array of objects based on one property of the objects. All objects in the array have this property, but this property is not always a number. The sort function I supply DOES convert the property into a number for the sort. I only mention it at all in case it's somehow part of the problem.

The problem is that the resulting array is NOT sorted. I added extra code inside the function so I can double-check the comparison being made, and confirm that the correct values are being compared. But the final array is in the exact same order as the initial array, even though (in the specific case that got me checking) the final element should be the first according to my criteria.

I should also note that the array I'm sorting from is NOT the same as the array I'm sorting INTO, as I need the original array kept unmodified.

I admit that the sort function is something I'm just starting to use, so I don't fully understand everything about it. The routine works in all other instances I've tried so far, but in all those other instances, the original array meets the sort criteria from the start, hence why only one instance has caught my attention so far.

Here's the relevant code:
JavaScript:
let newPool = this.data.buttons.sort((a, b) => {
    const x1 = this.getItemX(a), x2 =  this.getItemX(b);
    return x1 > x2;
})

Thanks in advance!
What does getItemX do and where is it coming from?
Hi there!

I believe your mistake is that in return for your function, you are using ">".

Although I don't know what the getItemX function is doing, I presume that it is retrieving the property you are using to sort/compare the array and converting it to a number, as you said, right?

Try do this instead:

JavaScript:
let myArr = [
    {position: 2},
    {position: 3},
    {position: 1}
]

myArr.sort((a, b) => {
    return a.position - b.position
})
@Eliaquim is correct, the sort() function expects a number, but the > (greater than) operator returns a boolean (which is either true or false).

The reason sort() expects a number is because there are 3 cases when comparing objects. Booleans can only handle 2 cases, as they can only be either true (1) or false (0). Therefore they are not suited for comparisons, as required by the sort() function. The 3 cases are:
  1. A is greater than B
  2. B is greater than A
  3. A and B are equal
Thus the number is either positive ( A is greater than B ), negative ( B is greater than A ), or zero ( A and B are equal ).

Most programmers simply use (a, b) => a - b as a comparison function, because it's functionally equivalent to:
JavaScript:
(a, b) => {
    if (a > b) return 1;
    if (a < b) return -1;
    return 0;
}
but much shorter.

Thus your code needs to return x1 - x2; instead of return x1 > x2; to work. And if you want to reverse the order, you only need to return x2 - x1; instead. Of course, this is assuming your getItemX() function returns a number, otherwise you obviously can't do x1 - x2 or x2 - x1.
My getItemX does indeed return a number. The various items I'm using can have coordinates and dimensions that can be either a hard number or some code that will need to be evaluated, so I have the appropriate getItem(whatever) to ensure that a number is returned. It lets me cut down on parameters and conditionals. The problem isn't there.
Most programmers simply use (a, b) => a - b as a comparison function, because it's functionally equivalent to:
JavaScript:
(a, b) => {
    if (a > b) return 1;
    if (a < b) return -1;
    return 0;
}
but much shorter.

Thus your code needs to return x1 - x2; instead of return x1 > x2; to work. And if you want to reverse the order, you only need to return x2 - x1; instead. Of course, this is assuming your getItemX() function returns a number, otherwise you obviously can't do x1 - x2 or x2 - x1.
I had seen it done that way in the base code, but wasn't sure why. It looks like that's my problem. I'll make the changes when I get some time and will report back.

Edit: The change didn't seem to work. I then tried to do the longhand version to see if that worked, and it DID work... but then screwed up something else using the data array. Apparently when an array is sorted, not only does it return the sorted array, the original array is modified.

I didn't dive too deeply into why changing to subtraction didn't work, I got distracted by the modified array issue. Too much stuff depends on the original array being untouched so I've got to redesign the entire function. But hopefully the redesign will allow me test stuff more thoroughly and figure the sort thing out.
Yes, the sort() function does indeed modify the original array.

You can fix this by sorting a copy of the array instead, the simplest way to get a copy is let copy = [...originalArray];

The three dots in front of originalArray are known as the "spread operator". It's basically the equivalent to doing let copy = [originalArray[0], originalArray[1], originalArray[2], /* and so on */];



As for why only the longhand code worked, my guess is that you didn't use the curly brackets {}. That's my bad for not explaining.

The sort() function expects a function as argument. That function is what the sort() function uses to compare two items (in this case a and b).

You are passing a so-called "arrow function" as argument. An arrow function is built like this: arguments => code

When your function expects 0 or more than 1 argument, the arguments part must have round brackets (), for example: () => { /* code */ } for 0 arguments, or (a, b) => { /* code */ } for 2 arguments a and b.

When your function expects only 1 argument, you can use round brackets, but don't have to, so a => { /* code */ } is valid, just like (a) => { /* code */ } is.

The code part is a little bit more complex.

When you only need to execute a single line, you don't need the curly brackets {}, and you also don't need to return.

But when you need to execute multiple lines of code, you need to use curly brackets, otherwise JavaScript doesn't know which line is still part of the arrow function, and which line isn't. Also, when you use curly brackets, you must return if you need the function to return something (otherwise it returns undefined).

Therefore, (a, b) => a - b; is a valid arrow function that returns the difference between a and b, as is (a, b) => { a - b; }, which only returns undefined, and (a, b) => { return a - b; }, which returns the difference between a and b.

However, the arrow function (a, b) => const x1 = this.getItemX(a), x2 = this.getItemX(b); x1 - x2; won't work, because x1 - x2; is no longer part of the arrow function, and also isn't returning anything.



I hope this helped.
Yes, the sort() function does indeed modify the original array.

You can fix this by sorting a copy of the array instead, the simplest way to get a copy is let copy = [...originalArray];

The three dots in front of originalArray are known as the "spread operator". It's basically the equivalent to doing let copy = [originalArray[0], originalArray[1], originalArray[2], /* and so on */];



As for why only the longhand code worked, my guess is that you didn't use the curly brackets {}. That's my bad for not explaining.

The sort() function expects a function as argument. That function is what the sort() function uses to compare two items (in this case a and b).

You are passing a so-called "arrow function" as argument. An arrow function is built like this: arguments => code

When your function expects 0 or more than 1 argument, the arguments part must have round brackets (), for example: () => { /* code */ } for 0 arguments, or (a, b) => { /* code */ } for 2 arguments a and b.

When your function expects only 1 argument, you can use round brackets, but don't have to, so a => { /* code */ } is valid, just like (a) => { /* code */ } is.

The code part is a little bit more complex.

When you only need to execute a single line, you don't need the curly brackets {}, and you also don't need to return.

But when you need to execute multiple lines of code, you need to use curly brackets, otherwise JavaScript doesn't know which line is still part of the arrow function, and which line isn't. Also, when you use curly brackets, you must return if you need the function to return something (otherwise it returns undefined).

Therefore, (a, b) => a - b; is a valid arrow function that returns the difference between a and b, as is (a, b) => { a - b; }, which only returns undefined, and (a, b) => { return a - b; }, which returns the difference between a and b.

However, the arrow function (a, b) => const x1 = this.getItemX(a), x2 = this.getItemX(b); x1 - x2; won't work, because x1 - x2; is no longer part of the arrow function, and also isn't returning anything.



I hope this helped.
I already knew a lot of that, simply because I've started using forEach and filter more and more lately, so arrow functions I MOSTLY already had figured out, at least enough to not break anything via function misuse. My screwups were generally my own fault INSIDE the functions. 😛

I think I was doing the function in one line without brackets, without a return. (I've since deleted the original code for my rewrite, so I don't recall EXACTLY) My rewrite IS using the brackets AND a return, and SO FAR it seems to work. But I'm rewriting it again because I realized I was overcomplicating my solution, both for this specific issue as well as the function as a whole.

Instead of copying the entire array, which I don't need MOST of the data in each element for this, I'm instead prepping the data with a new data array containing only the parts I need, and cutting out the function calls by using them in the new array and storing the final numbers, since they're not going to change during this whole thing. Should cut down time complexity in the actual sorting. The array also contains the index of each item from the original array, so I can sort the new array without worrying about the modifications, as well as perhaps being able to use the simple shorthand sort method. Also simplifies GETTING the object I need from the original array later on.

Once I get that set up and tested, I'll either have this solved and can have it closed, or I'll still have a problem and will be back for part 3 of "Sorting and I Don't Get Along". I'm hoping to avoid the trilogy. 😛

Original thread: https://forums.rpgmakerweb.com/threads/sorting-an-array-of-objects-not-working.137956/