LINQ icon indicating copy to clipboard operation
LINQ copied to clipboard

OrderBy doesn't work

Open royigoldi opened this issue 10 years ago • 6 comments

Hi,

I tried to run the follwing code:

let t :any[] = [{name:'royi'}, {name:'david'}, {name:'barak'}, {name:'moshe'}];
 let o = asEnumerable(t).OrderBy(s=> s.name).ToArray();
console.log(o);

It print in the original order...

I also try to define name string propety in type script class and orderby this property also do nothing..

Thanks, Royi

royigoldi avatar Nov 21 '16 12:11 royigoldi

It looks like sorting is not a trivial matter if done properly. Article here skims over few issues.

ENikS avatar Nov 29 '16 19:11 ENikS

Hi,

when there will be fix?

thanks, royi

royigoldi avatar Dec 04 '16 09:12 royigoldi

Family matters, will do as soon as possible

ENikS avatar Dec 04 '16 16:12 ENikS

As a workaround, while I am fixing the issue, you may provide your own comparison function to fix the error in your code

ENikS avatar Dec 06 '16 19:12 ENikS

Just experienced the same problem using OrderBy the first time for objects with string or date property.

I hope for a new year release until then we can use:

http://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value-in-javascript http://stackoverflow.com/questions/39348556/typescript-sort-object-by-object-in-array

I prefer the linq flavor ;-)

bastienJS avatar Dec 19 '16 21:12 bastienJS

Hi, It seems the default comparer algorithm doesn't work with Javascript string http://stackoverflow.com/questions/51165/how-do-you-do-string-comparison-in-javascript

This fixes the problems. let t :any[] = [{name:'royi'}, {name:'david'}, {name:'barak'}, {name:'moshe'}]; let o = asEnumerable(t).OrderBy(s=> s.name, (a,b)=>(a.localeCompare(b)) ).ToArray(); console.log(o);

A generic comparer function that should work on numbers and strings

let comparer  = <T> (a: T,b: T) : number => {
    if (typeof(a) === 'string' && typeof(b) === 'string' ){
        return (<string>a).localeCompare(<string>b);
    } else {
        return ( <any>a - <any>b );
    }
}

But maybe this can be written better... it's my fourth week with Typescript.

chenglabs avatar Dec 30 '16 09:12 chenglabs