简体   繁体   English

按属性值对对象的javascript数组进行排序并按条件重新排序

[英]Sort javascript array of objects by property value and reorder by condition

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"}] [{"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 值之后没有 S 值,我会重新排列排序。 P value should be low priority if there is no S value.如果没有 S 值,P 值应该是低优先级。 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"}] [{"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"}]

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; }

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 .然后你可以在你的compare使用该函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM