admin管理员组

文章数量:1356097

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 es 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?

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 es 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?

Share Improve this question edited Apr 21, 2015 at 18:47 Turing85 20.2k7 gold badges39 silver badges65 bronze badges asked Apr 21, 2015 at 18:40 jijojijo 8255 gold badges21 silver badges38 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 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 parison 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"]

If you want to allow for, count and hoist multiple instances of those strings: http://jsfiddle/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);

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;

}

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

本文标签: sorting of array manually in javascriptStack Overflow