3

Can anybody help me.

I am trying to sort strings from array

var someArray= ["3a445a_V1", "3", "2a33s454_V1", "1", "3_V2", "2s4a34s3_V2", "234343"];

const [record] = someArray.map(r => parseFloat(r.replace('_V','.'))).sort((a,b) => a < b);

console.log(record)
//it returns 3a445a.1

JFIDDLE

In browser console.log it works fine, not in typescript?

typescript it is giving below error Error:

error TS2345: Argument of type '(a: number, b: number) => boolean' is not 
assignable to parameter of type '(a: number, b: number) => number'.
      Type 'boolean' is not assignable to type 'number'.

Any idea? thanks in advance

4
  • 3
    (a,b) => a < b is not a valid comparison function. As typescript says, it's supposed to return a number, not a boolean. Commented Feb 11, 2018 at 14:20
  • "In browser console.log it works fine' It doesn't, actually, it just happens that your data don't reveal the problems with it. Commented Feb 11, 2018 at 14:20
  • @T.J. Crowder , i have just created fiddle, please check and guide me Commented Feb 11, 2018 at 14:23
  • 1
    @t.j. im still wondering how i overlooked that... Commented Feb 11, 2018 at 14:27

2 Answers 2

19

.sort((a,b) => a < b) is incorrect. The TypeScript message is right: The sort callback should return a number, not a boolean.

Instead: .sort((a,b) => a - b) (- instead of <). Or b - a to sort the other way. This is because the sort callback should return a negative number if a comes before b, 0 if their order doesn't matter, and a positive number if b comes before a. Since you seem to want ascending order, that's a - b so that if a is less than b, it returns a negative number, etc. b - a does a descending sort.

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

1 Comment

Thank you, didn't know that I could just write b - a!
0

you can also use .sort((a,b) => Number(a>b)). This worked for me just fine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.