262

I've been trying to figure out a very strange issue I ran into with typescript. It was treating an inline Boolean expression as whatever the first value's type was instead of the complete expression.

So if you try something simple like the following:

var numericArray:Array<number> = [2,3,4,1,5,8,11];

var sorrtedArray:Array<number> = numericArray.sort((n1,n2)=> n1 > n2);

TryIt

You will get an error on your sort method saying the parameters do not match any signature of the call target, because your result is numeric and not Boolean. I guess I'm missing something though cause I'm pretty sure n1>n2 is a Boolean statement.

0

9 Answers 9

406

Numbers

When sorting numbers, you can use the compact comparison:

var numericArray: number[] = [2, 3, 4, 1, 5, 8, 11];

var sortedArray: number[] = numericArray.sort((n1,n2) => n1 - n2);

i.e. - rather than <.

Other Types

If you are comparing anything else, you'll need to convert the comparison into a number.

var stringArray: string[] = ['AB', 'Z', 'A', 'AC'];

var sortedArray: string[] = stringArray.sort((n1,n2) => {
    if (n1 > n2) {
        return 1;
    }

    if (n1 < n2) {
        return -1;
    }

    return 0;
});

Objects

For objects, you can sort based on a property, bear in mind the above information about being able to short-hand number types. The below example works irrespective of the type.

var objectArray: { age: number; }[] = [{ age: 10}, { age: 1 }, {age: 5}];

var sortedArray: { age: number; }[] = objectArray.sort((n1,n2) => {
    if (n1.age > n2.age) {
        return 1;
    }

    if (n1.age < n2.age) {
        return -1;
    }

    return 0;
});
Sign up to request clarification or add additional context in comments.

7 Comments

Could some one explain why, for the less-than test, '[email protected]' returns true for less than '[email protected]'? e.g.: let myTest = ('[email protected]' < '[email protected]'); // returns true for me... :(
in the second case you can use localeCompare() to compare strings in the current locale, which returns a number
Please explain me, How (n1,n2)=>n1-n2 expression will execute or work..??
@RahulChaudhari in the number example, it's a function that takes the numbers n1 and n2, within the function it returns n1-n2, which will either be a positive number, zero, or a negative number. This tells the sort operation whether the items need to be switched or not, thus enabling sorting.
its can be possible filter with different proprty
|
233

The error is completely correct.

As it's trying to tell you, .sort() takes a function that returns number, not boolean.

You need to return negative if the first item is smaller; positive if it it's larger, or zero if they're equal.

Comments

29

Great answer Sohnee. Would like to add that if you have an array of objects and you wish to sort by key then its almost the same, this is an example of one that can sort by both date(number) or title(string):

    if (sortBy === 'date') {
        return n1.date - n2.date
    } else {
        if (n1.title > n2.title) {
           return 1;
        }
        if (n1.title < n2.title) {
            return -1;
        }
        return 0;
    }

Could also make the values inside as variables n1[field] vs n2[field] if its more dynamic, just keep the diff between strings and numbers.

2 Comments

Commenting on answers should be done using the comments function.
@Nicktar It's probably posted as an answer for the formatting. But it doesn't do any harm anyway
14
let numericArray: number[] = [2, 3, 4, 1, 5, 8, 11];

let sortFn = (n1 , n2) => number { return n1 - n2; }

const sortedArray: number[] = numericArray.sort(sortFn);

Sort by some field:

let arr:{key:number}[] = [{key : 2}, {key : 3}, {key : 4}, {key : 1}, {key : 5}, {key : 8}, {key : 11}];

let sortFn2 = (obj1 , obj2) => {key:number} { return obj1.key - obj2.key; }

const sortedArray2:{key:number}[] = arr.sort(sortFn2);

3 Comments

n1 - n2 is negative when n1 < n2, positive when n1 > n2 and 0 when n1 == n2
Thanks! I changed it for this: myArray.sort((a, b): number => { return a.NumberProp - b.NumberProp; });
{key:number} in sorting function is not working in my typescript file... removed it... now working, where I have key:Date data type
12

Sort Mixed Array (alphabets and numbers)

function naturalCompare(a, b) {
   var ax = [], bx = [];

   a.replace(/(\d+)|(\D+)/g, function (_, $1, $2) { ax.push([$1 || Infinity, $2 || ""]) });
   b.replace(/(\d+)|(\D+)/g, function (_, $1, $2) { bx.push([$1 || Infinity, $2 || ""]) });

   while (ax.length && bx.length) {
     var an = ax.shift();
     var bn = bx.shift();
     var nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);
     if (nn) return nn;
   }

   return ax.length - bx.length;
}

let builds = [ 
    { id: 1, name: 'Build 91'}, 
    { id: 2, name: 'Build 32' }, 
    { id: 3, name: 'Build 13' }, 
    { id: 4, name: 'Build 24' },
    { id: 5, name: 'Build 5' },
    { id: 6, name: 'Build 56' }
]

let sortedBuilds = builds.sort((n1, n2) => {
  return naturalCompare(n1.name, n2.name)
})

console.log('Sorted by name property')
console.log(sortedBuilds)

Comments

10

The easiest way seems to be subtracting the second number from the first:

var numericArray:Array<number> = [2,3,4,1,5,8,11];

var sortedArray:Array<number> = numericArray.sort((n1,n2) => n1 - n2);

https://alligator.io/js/array-sort-numbers/

Comments

2

For strings I do this,

let unSortedArray = ['d', 'b', 'c', 'a'];
let sortedArray = unSortedArray.sort((x, y) => x > y ? 1 : x < y ? -1 : 0)

which easily can be extended to more complex types e.g. dictionaries. In that case, instead of x, y use x.whicheverKey, y.whicheverKey e.g.

unSortedObjectArray.sort((x, y) => x.whicheverKey > y.whicheverKey ? 1 : x.whicheverKey < y.whicheverKey ? -1 : 0)

Comments

1

i use this

type SortArrayType = <T>(arr: T[]) => T[];

const sortArray: SortArrayType = (arr) => {
  return arr.sort((a, b) => {
    const strA = JSON.stringify(a);
    const strB = JSON.stringify(b);
    if (strA < strB) {
      return -1;
    }
    if (strA > strB) {
      return 1;
    }
    return 0;
  });
};

Comments

0

I wrote this one today while trying to recreate _.sortBy in TypeScript, and thought I would leave it for anyone in need.

// ** Credits for getKeyValue at the bottom **
export const getKeyValue = <T extends {}, U extends keyof T>(key: U) => (obj: T) => obj[key] 

export const sortBy = <T extends {}>(index: string, list: T[]): T[] => {
    return list.sort((a, b): number => {
        const _a = getKeyValue<keyof T, T>(index)(a)
        const _b = getKeyValue<keyof T, T>(index)(b)
        if (_a < _b) return -1
        if (_a > _b) return 1
        return 0
    })
}

Usage:

It expects an array of generic type T, hence the cast for <T extends {}>, as well as typing the parameter and function return type with T[]

const x = [{ label: 'anything' }, { label: 'goes'}]
const sorted = sortBy('label', x)

** getByKey fn found here

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.