lontonglah
lontonglah

Reputation: 23

How do I sort an array by the first character in the string?

How do I sort this array?

Input: ['sfr2ta', '2ab', 'bbb1ddd']

Output: ['bbb1ddd', 'sfr2ta', '2ab']

Upvotes: 2

Views: 2400

Answers (3)

mipsc
mipsc

Reputation: 113

If you want to sort it by the first charachter then the output should be like this: ['2ab', 'bbb1ddd', 'sfr2ta'].

But if you want to sort it that letters come before nubmers, then you write something like:

    l = ['sfr2ta', '2ab', 'bbb1ddd'];
    
    lNums = []

    lStrs = []

    for( let s of l ) {
        if(s[0] >= 0 && s[0] <= 9){
            lNums.push(s);
        }
        else {
            lStrs.push(s);
        }
    }
    lNums.sort();
    lStrs.sort();
    l = lStrs.concat(lNums);
    console.log(l)

output: [ 'bbb1ddd', 'sfr2ta', '2ab' ]

Upvotes: 2

Rajneesh
Rajneesh

Reputation: 5308

We can do this with sort:

var s = ['sfr2ta', '2ab', 'bbb1ddd'];

var result = [...s.filter(n=>!Number(n[0])).sort((a,b)=>a[0].localeCompare(b[0])), ...s.filter(p=>Number(p[0]))];

console.log(result);

Upvotes: 0

yeerk
yeerk

Reputation: 2677

Depending on how you want zero length strings to act (""), this should work:

function sortByFirstCharacter(arr) {
    arr.sort((lhs, rhs) => {
        if(lhs === rhs) return 0;
        if(lhs === "") return -1;
        if(rhs === "") return +1;
        return (
            lhs[0] < rhs[0] ? -1
            : lhs[0] > rhs[0] ? +1
            : 0
        );
    });
    return arr;
}

Upvotes: 0

Related Questions