Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining then sorting Javascript arrays. Getting unpredictable results

this is how the data has been given to me, in an object w/ elements separated by the pipe char.

first i need to combine the two array and then sort alphabetically. the below example is a simplified example. but something is throwing the sort function off. the results are bizarre

carriersOne = ['St. Joseph\'s Medical Center | New York Health Care Insurance Company |    Some Other Company'];
carriersTwo = ['Advantage Care | Chicago Insurance Company | Hospital Insurance    Corporation'];

carriersOne = carriersOne[0].split('|');
carriersTwo = carriersTwo[0].split('|');

allCarriers = carriersOne.concat(carriersTwo);
allCarriers.sort();

count = allCarriers.length;

for(i=0;i<count;i++) {
alert(allCarriers[i]);
}

What you get is:

  Chicago Insurance Company
  Hospital Insurance Corporation
  New York Health Care Insurance Company
 Some Other Company
Advantage Care
St. Joseph's Medical Center

w-t-bleep order is that? note: if you use single names, or predictable first and last names, it combines and sorts fine.

like image 554
TopTomato Avatar asked Apr 24 '26 17:04

TopTomato


1 Answers

That's because you're not stripping off the surrounding spaces, especially the leading spaces. The sorting is off because a space comes before any letter. The below code should fix it, assuming the whole line has no surrounding white space:

// split on pipe and surrounding white space
var splitRe = /\s*\|\s*/;

carriersOne = carriersOne[0].split(splitRe);
carriersTwo = carriersTwo[0].split(splitRe);
like image 120
Ja͢ck Avatar answered Apr 26 '26 06:04

Ja͢ck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!