Built-in sort
joeworkman opened this issue · 7 comments
I know that its easy enough for me to sort my data after a search, but it could be a nice feature to be able to define a field that the array should be sorted by.
Thanks for making this, its really saving the day!
Thanks for making this, its really saving the day!
Quite welcome. I no longer can recall what the project was that got it started. It is my hope that all of this will be made unnecessary by some version or ES in the future. In the meantime...
it could be a nice feature to be able to define a field that the array should be sorted by.
Why not just use the build-in JS capabilities?
> list = [{name:"Jim", age:35},{name:"Sally",age:22},{name:"Alex",age:55}]
> list.sort((a,b) =>{return a.age - b.age})
[ { name: 'Sally', age: 22 },
{ name: 'Jim', age: 35 },
{ name: 'Alex', age: 55 } ]
> list.sort( (a,b) => { return (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0)} )
[ { name: 'Alex', age: 55 },
{ name: 'Jim', age: 35 },
{ name: 'Sally', age: 22 } ]
You are correct. I just though that it would be nice if I could simply give a list of fields to sort by and the library would take care of it. Its purely a convenience thing...
Hmm. Can you give an example of what the interface would look like?
Sorry. I totally missed your reply. I was thinking something like this to sort the data by a specific property.
{name:"John",age:30,_sort:"name"}
Well, you could do:
> list = [{name:"Jim", age:35},{name:"Sally",age:22},{name:"Alex",age:55}]
> search.matchArray(list, searchTerms).sort( (a,b) => { return (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0)} )
Granted, it would be easier to do:
search.matchArray(list, {age: 30, _sort: "name"} )
But then you need to think about integer vs string, ascending vs descending, case-sensitive vs case-insensitive. I am a little concerned about thus turning into something bigger than a small convenience. There have to be decent sort libraries around?
Good points on the integer sorting. I could see this as not being as simple a solution as I originally intended.
I tend to think in the Unix philosophy of doing one thing, and doing it well, and having a well-defined (normally char stream) interface. In this case, matchArray()
always returns a JS array, which can be chained to another sorting function.
I think we should let this one go for now.