How to sort an array of objects by multiple fields?

后端 未结 30 2404
北恋
北恋 2020-11-21 11:34

From this original question, how would I apply a sort on multiple fields?

Using this slightly adapted structure, how would I sort city (ascending) & then price (

30条回答
  •  自闭症患者
    2020-11-21 12:08

    Here is mine for your reference, with example:

    function msort(arr, ...compFns) {
      let fn = compFns[0];
      arr = [].concat(arr);
      let arr1 = [];
      while (arr.length > 0) {
        let arr2 = arr.splice(0, 1);
        for (let i = arr.length; i > 0;) {
          if (fn(arr2[0], arr[--i]) === 0) {
            arr2 = arr2.concat(arr.splice(i, 1));
          }
        }
        arr1.push(arr2);
      }
    
      arr1.sort(function (a, b) {
        return fn(a[0], b[0]);
      });
    
      compFns = compFns.slice(1);
      let res = [];
      arr1.map(a1 => {
        if (compFns.length > 0) a1 = msort(a1, ...compFns);
        a1.map(a2 => res.push(a2));
      });
      return res;
    }
    
    let tstArr = [{ id: 1, sex: 'o' }, { id: 2, sex: 'm' }, { id: 3, sex: 'm' }, { id: 4, sex: 'f' }, { id: 5, sex: 'm' }, { id: 6, sex: 'o' }, { id: 7, sex: 'f' }];
    
    function tstFn1(a, b) {
      if (a.sex > b.sex) return 1;
      else if (a.sex < b.sex) return -1;
      return 0;
    }
    
    function tstFn2(a, b) {
      if (a.id > b.id) return -1;
      else if (a.id < b.id) return 1;
      return 0;
    }
    
    console.log(JSON.stringify(msort(tstArr, tstFn1, tstFn2)));
    //output:
    //[{"id":7,"sex":"f"},{"id":4,"sex":"f"},{"id":5,"sex":"m"},{"id":3,"sex":"m"},{"id":2,"sex":"m"},{"id":6,"sex":"o"},{"id":1,"sex":"o"}]
    

提交回复
热议问题