1

I have an array of objects Like :

    var newArray = [
      {value : "P1"},
      {value : "P2/S2"},
      {value : "P2"},
      {value : "P1"},
      {value : "P1/S2"},
      {value : "P1/S3"},
      {value : "P2/S1"},
      {value : "P1/S3"},
      {value : "P2/S2"},
      {value : "P1"},
      {value : "P2"},
      {value : "P3"}
    ];
    
    function compare( a, b ) {
      if ( a.value < b.value ){
        return -1;
      }
      if ( a.value > b.value ){
        return 1;
      }
      return 0;
    }
    
    newArray.sort( compare );
    console.log(newArray);

[{"value":"P1"},{"value":"P1"},{"value":"P1"},{"value":"P1/S2"},{"value":"P1/S3"},{"value":"P1/S3"},{"value":"P2"},{"value":"P2"},{"value":"P2/S1"},{"value":"P2/S2"},{"value":"P2/S2"},{"value":"P3"}]

But here i have a rearrangement in sorting if there is no S value after P value. P value should be low priority if there is no S value. I am expecting a result like this :

[{"value":"P1/S2"},{"value":"P1/S3"},{"value":"P1/S3"},{"value":"P1"},{"value":"P1"},{"value":"P1"},{"value":"P2/S1"},{"value":"P2/S2"},{"value":"P2/S2"},{"value":"P2"},{"value":"P2"},{"value":"P3"}]

2 Answers 2

3

You could add a suffix and sort smaller strings to the bottom.

function compare({ value: a }, { value: b }) {
    a += 'ZZZ';
    b += 'ZZZ';
    return a > b || -(a < b);
}

var array = [{ value: "P1" }, { value: "P2/S2" }, { value: "P2" }, { value: "P1" }, { value: "P1/S2" }, { value: "P1/S3" }, { value: "P2/S1" }, { value: "P1/S3" }, { value: "P2/S2" }, { value: "P1" }, { value: "P2" }, { value: "P3" }];
   
array.sort(compare);

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

0

Maybe computing values weight? For example:

function computeWeight(str) {
  var weight = 0;
  for (var i = str.length-1; i >= 0; i--) {
    weight = weight + (str.charCodeAt(i) * Math.pow(10, i));
  }
  return weight;
}

this way longer strings will have a greater weight than the smaller ones because they have more symbols. Then you can use that function in your compare.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.