Trying to sort a custom JavaScript object

后端 未结 5 1048
时光说笑
时光说笑 2021-01-01 04:18

I\'m not too good at JS, but have survived thus far. I\'m creating a sort-of complex JS object and wanting to sort it. The object\'s structure looks like this:

<         


        
5条回答
  •  星月不相逢
    2021-01-01 05:13

    You should be able to sort an array of objects, based on the object attributes, by writing a custom sort function like so:

    function customSortByPID(a,b) {
      if (a.ProductID > b.ProductID)
      {
          return 1;
      }
      else if (a.ProductID < b.ProductID)
      {
          return -1;
      }
      return 0;
    }
    

    Where ProductID is an attribute of your object. You would call it like this:

      myArray.sort(customSortByPID);
    

    That should at least get you started on how to write custom sort functions. Be aware that JavaScript is not strongly typed, which could lead to unexpected sorting behavior (treating an int like a string).

    ** DISCLAIMER ** I didn't test any of the above, it's just off the top of my head.

提交回复
热议问题