2

How do I sort this array?

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

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

4
  • What is the criteria for sorting it that way? Commented Jun 21, 2020 at 3:42
  • string that contains letters in the first position will be prioritise first @Abion47 Commented Jun 21, 2020 at 3:49
  • Sorry, didn't fully read the question. In which way would you like to order your characters? The conventional ascii ordering puts "2" before "b" (as in, in JavaScript "2" < "b"). Commented Jun 21, 2020 at 3:58
  • How is sorting based on the first character different from sorting based on the whole strings? Do you want the sort to deliberately ignore everything except the first character? Commented Jun 21, 2020 at 4:28

3 Answers 3

2

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' ]
Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

1 Comment

thanks, but the string that contains letters in the first position needs to appear first. the code will put 2ab as the first
0

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);

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.