Sort an array except one element in JavaScript

前端 未结 10 2520
感动是毒
感动是毒 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 01:56

    The .sort function takes a callback as an argument. This callback will be passed two values. The job of the callback is to determine which one is bigger. It does this by returning a numeric value.

    Let's say the arguments passed to your callback are called a and b. I have bolded the values your callback should return for each case

    • a < b Less than 0
    • a > b Greater than 0
    • a = b Equal to 0

    This is easy to remember because, for numerical values, you can use a - b to get a desired return value.

    Now, despite most callbacks passed to .sort are very small, it is possible to pass in very complicated functions to suit your need. In this case,

    • If a.key is None, a < b
    • If b.key is None, b < a
    • Else, use our current sort mechanism.

    We could take advantage of the return statement exiting once it's called. So, let's implement this function bullet-by-bullet.

    To make our code Super Good, let's return "0" when the two values are equal (even when those two values have keys of "None")

    Comparison.sort(function(a, b) {
      // Our extra code
      if(a.key === b.key) return 0; // Zero (a = b)
      if(a.key === "None") return -1; // Negative (a < b)
      if(b.key === "None") return 1; // Positive (b < a)
    
      // Old sort
      if(a.key < b.key) return -1;
      if(b.key < a.key) return 1;  
    })
    

    Golfing that solution

    There are ways to make that solution shorter (and, perhaps, more readable) -- which is important when code is doing simple tasks.

    The first thing to note is that the final line, if(b.key < a.key) return -1 could be shortened to return -1;. This is because if a.key < b.key or b.key = a.key we would've returned on an earlier line.

    The second thing to note is that using ES6 syntax (which might not be compatible with older browsers, particularly regarding Internet Explorer), we can use arrow function notation for the callback.

    function(a, b) {} could become (a, b) => {}

    The third thing to note is that we can convert the below block of code

    if(a.key < b.key) return -1;
    if(b.key < a.key) return 1;
    

    into

    return (b.key < a.key) - (a.key < b.key)
    

    That's because true is treated as 1, and false as 0 when regarding subtraction. true - false is 1 - 0 is 1, false - true is 0 - 1 is -1, and 0 - 0 is 0. There will never be a situation where true - true occurs.

提交回复
热议问题