0

I'm working on converting an array utilities file from js to typescript on an open source project. It's been pretty easy to convert most functions, but I'm not understanding what this one is doing.

/**
 * sort array by numeric by numeric property values
 * of object entries. null entries are treated as 0.
 * array entries must be objects.
 * @param {object[]} arr
 * @param {string} prop - numeric property to sort on.
 */
export const propSort = (arr,prop) => {

    arr.sort( (a,b)=>{
        return ( a[prop] || 0 ) - ( b[prop] || 0 );
    });

}

I have a description for what the function is supposed to be doing, as is listed above the function. But I don't understand the syntax. Apparently prop is supposed to be a string. But if that's the case, what exactly are a, b? How do you get the value out of an array using a string? And are there any pitfalls in converting this function to typescript?

Tiny Tim
  • 207
  • 1
  • 6
  • `a` and `b` are two separate elements of `arr`. You can refer to [`Array.prototype.sort()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) for additional info; specifically, any contained references to the `compareFn` argument – Arman Charan May 29 '23 at 04:59

1 Answers1

2

This function is essentially a wrapper around the .sort() method of arrays. If you pass .sort() a callback, it will pass that call back the two elements it is comparing for sorting purposes. Your callback then returns a value to determine which of the two elements should come first by returning a positive value (a comes after b), negative value (a comes before b), or zero (they are equal and their relative order doesn't matter).

The propSort() function just runs .sort() and returns the result, but passes .sort() a callback function. The idea of the callback function is that every element of arr is an object and you want to sort each object by a property that every object has.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • Didn't realize ChatGPT answer were banned, thanks for the heads up. Sorry about that. It makes sense that they would be banned though, it won't happen again :) – Tiny Tim May 29 '23 at 05:49