Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript custom sort function to prioritize a letter

I already have a sorted array (can contain up to 1,000 items), I just want to take the block of items that start with the specified character and move them to the top.

// Before sort
{ "alpha", "beta", "delta", "delta frequency", "gamma", "theta" } 

// After sort with "d" as the specified letter
{ "delta", "delta frequency", "alpha", "beta", "gamma", "theta" }

I'm not familiar enough with JavaScript to know a good way to do this. My first thought was to iterate through each item and see if the index of the specified start character was "0" to find the first and last array index, and moving that range to the top of the array, but that seemed like it might be wasteful. Is there a better way?

like image 836
StronglyTyped Avatar asked Sep 12 '26 11:09

StronglyTyped


2 Answers

var array = [ "alpha", "beta", "delta", "delta frequency", "gamma", "theta" ];
var startingWithD = array.filter(function(s) {
    return s[0] == "d";
});
var others = array.filter(function(s) {
    return s[0] != "d";
});
array = startingWithD.concat(others);
like image 178
zch Avatar answered Sep 15 '26 01:09

zch


Here's a sorting algorithm, which will actually sort the array weighting strings that start with "d" to the beginning. Note that I've rearranged the beginning array a bit, to show that the sorting works correctly.

array = [ "beta", "alpha", "delta frequency", "delta 2", "delta 1", "delta", "gamma", "theta" ];
array.sort(function(a,b) {
    if (a[0] == "d" && b[0] != "d") {
        return -1
    }
    if (b[0] == "d" && a[0] != "d") {
        return 1;
    }
    return a > b;
});

console.log(array);

http://jsfiddle.net/ryanbrill/RqfgL/

like image 27
ryanbrill Avatar answered Sep 15 '26 01:09

ryanbrill



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!