CodingCowboy
CodingCowboy

Reputation: 63

Sorting an array containing text with spaces

I'm trying to sort an array containing strings. Each value typically has the following structure: [registration number][ ][account number][, ][account name]

But in rare cases a value does not have the first 4 reg.numbers + a space.

This is an example of an array:

var accounts = ["1111 12345678, Account1", 
              "2222 12345678, Account2", 
              "11345678, Account3", 
              "12345678, Account4", 
              "3333 12345678, Account5"];

I can sort accounts by using accounts.sort(), and that works almost fine. BUT I would like to have the values sorted AND have the values without reg.no appear last in the sorted array (still sorted alpabetically).

So sorting the accounts array should result in this list:

1111 12345678, Account1
2222 12345678, Account2
3333 12345678, Account5
11345678, Account3
12345678, Account4

Any good suggestion to this?

Upvotes: 4

Views: 2423

Answers (3)

Aditya Bhave
Aditya Bhave

Reputation: 1028

  1. Get all items that contains > 2 spaces. Sort this array.
  2. Get all items that contains === 2 spaces.

let arr = ["3333 12345678, Account5","1111 12345678, Account1", 
              "2222 12345678, Account2", 
              "11345678, Account3", 
              "12345678, Account4", 
              ];
              
              
let arr1 = arr.filter((a) => {
  return a.split(' ').length > 2;
});

let sortedArr = arr1.sort();

let appendArr = arr.filter((a) => {
  return a.split(' ').length === 2;
});

sortedArr = [...sortedArr, ...appendArr];

console.log(sortedArr);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386550

You culd check for leading numbers and sort this numbers to top.

const hasLeading = s => /^\S+\s\S+\s\S+$/.test(s);

var accounts = ["1111 12345678, Account1", "2222 12345678, Account2", "11345678, Account3", "12345678, Account4", "3333 12345678, Account5"];

accounts.sort((a, b) => hasLeading(b) - hasLeading(a) || a > b || -(a < b));

console.log(accounts);

Upvotes: 4

KingGary
KingGary

Reputation: 638

You can do it like this:

var accounts = ["1111 12345678, Account1", 
              "2222 12345678, Account2", 
              "11345678, Account3", 
              "12345678, Account4", 
              "3333 12345678, Account5"];


function compare(a, b) {
  var aArr = a.split(' ');
  var bArr = b.split(' ');
  if (aArr.length > 2 && bArr.length > 2) {
    return aArr[2] > bArr[2];
  } else if (aArr.length > 2) {
    return -1;
  }  else if (bArr.length > 2) {
    return 1;
  } else {
    return aArr[1] > bArr[1];
  }
}

console.log(accounts.sort(compare))

Upvotes: 0

Related Questions