How to sort an array of objects with multiple field values in JavaScript

前端 未结 5 1887
迷失自我
迷失自我 2020-12-10 13:56

I found a great method to sort an array of objects based on one of the properties as defined at:

Sort array of objects by string property value in JavaScript

5条回答
  •  感动是毒
    2020-12-10 14:24

    The easiest way to perform a Javascript Multi-Criteria Sort (or Multi-Parameter Sort), is to use .sort, concatenate the multiple parameters together, and compare the two stings.

    For example:

    data.sort(function (a, b) {
    
      var aConcat = a["property1"] + a["property2"];
      var bConcat = b["property1"] + b["property2"];
    
      if (aConcat > bConcat) {
        return 1;
      } else if (aConcat < bConcat) {
        return -1;
      } else {
        return 0;
      }
    
    });
    

    I've included a JsFiddle Script here: http://jsfiddle.net/oahxg4u3/6/

提交回复
热议问题