2

I have an array of strings like below.

ABC
QRS
DEF
HIJ
TUV
KLM
NOP

I need to sort this array in javascript in alphabetical order, except for few values which is already known. ie I need DEF and NOP comes in the first 2 positions and sort rest of the array alphabetically in ascending order. Here is what I've written to sort the entire array in alphabetical order, now I need the 2 values in the first 2 positions.

array.sort(function(a,b){return ((a < b) ? -1 : (a > b) ? 1 : 0)});

Expected result.

DEF
NOP
ABC
HIJ
KLM
QRS
TUV

The contents of the array is dynamic, so if the array has DEF or NOP, then those should be on top, if else, it should be sorted alphabetically. Whats the best way to approach this?

4 Answers 4

5

I think the most straightforward way would be to remove the known elements separately instead of trying to incorporate them into the sort. That way, you can also just sort without a comparison function.

function sortWithKnownPrefix(prefix, arr) {
    // Get the non-prefix elements
    var rest = arr.filter(function (item) {
        return prefix.indexOf(item) === -1;
    });

    // Concatenate the prefix and the sorted non-prefix elements
    return prefix.concat(rest.sort());
}

sortWithKnownPrefix(
    ["DEF", "NOP"],
    ["ABC", "QRS", "DEF", "HIJ", "TUV", "KLM", "NOP"]
)
// ["DEF", "NOP", "ABC", "HIJ", "KLM", "QRS", "TUV"]
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to allow for, count and hoist multiple instances of those strings: http://jsfiddle.net/4hgnjqas/1/

The following will count all known instances of the strings you want to hoist to the front, remove them from the existing array, sort it, then add the same number of "DEF"s and "NOP"s to the array.

var hoist = {"NOP":0, "DEF":0}

for(var p in hoist)
    while(array.indexOf(p)>-1){
        array.splice(array.indexOf(p),1);
        hoist[p]++;
    }
arr.sort();
for(var p in hoist){
    for(var i=0;i<hoist[p];i++)
        array.unshift(p);
}
console.log(array);

Comments

0

This will reposition 'DEF' and 'NOP' after sorting the rest of the items:

function customSort(array) {

  array  = array.sort(function(a,b){
    return (a < b) ? -1 : (a > b) ? 1 : 0;
  });

  var NOPIndex = array.indexOf('NOP');
  if (NOPIndex > -1)
    array.unshift(array.splice(NOPIndex, 1)[0]);

  var DEFIndex = array.indexOf('DEF');
  if (DEFIndex > -1)
    array.unshift(array.splice(DEFIndex, 1)[0]);

  return array;

}

Comments

0

this could be the simpler one

var arr = ['ABC','QRS','DEF','HIJ','TUV','KLM','NOP']
var exclude = ['DEF', 'NOP'];

arr.sort(function(a,b) {
    if(exclude.indexOf(a) > -1 && exclude.indexOf(b) > -1)
        return ((a < b) ? -1 : (a > b) ? 1 : 0);
    if(exclude.indexOf(b) > -1) 
        return 1;
    return ((a < b) ? -1 : (a > b) ? 1 : 0)
});

alert(JSON.stringify(arr))  //result

JS Fiddle *UPDATED

2 Comments

Nice, except the order of 'DEF' and 'NOP' is reversed.
This looks good, but I need to maintain the order of exclude array in the result array..

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.