Sort an array except one element in JavaScript

前端 未结 10 2527
感动是毒
感动是毒 2021-02-12 01:31

I have an array and I am sorting it but I need to sort everything except one element of my array.

My array is:

var Comparison = [
    {key: \"None\", val         


        
10条回答
  •  醉梦人生
    2021-02-12 02:16

    If you want it positioned at the top you could just return -1 or you could return 1 if you want your item at the bottom of the list.

    You do not need multiple if's for the firstly or lastly positioned item which you want to exclude from the general sort.

    this.Comparison.sort(function (a, b) {
      if(a.key == b.key) return 0;
      if (a.key == 'None' || b.key == 'None') return -1;
    
      if (a.key < b.key)
          return -1;
      if (a.key > b.key)
          return 1;
      return 0;
    });
    

提交回复
热议问题