sorting array of arrays using one of their indexes

前端 未结 2 1877
再見小時候
再見小時候 2021-01-28 11:37

I have an array with different values in it and I\'d like to sort it by the numeric value in one of the indexes

const arr = [
  [\'foo\', var, 5],
  [\'fee\', v         


        
相关标签:
2条回答
  • 2021-01-28 12:08

    You can use sort like this:

    arr.sort((a,b) => {
      return a[2] < b[2] // To sort in descending order
      // return a[2] > b[2] // To sort in ascending order
    })
    

    Example:

    var arr = [
      ['foo', 'fifth', 5],
      ['fee', 'seventh', 7],
      ['faa', 'third', 3]
    ];
    
    var sortedArr = arr.sort(function(a,b){
      return a[2] < b[2]
    });
    
    console.log(sortedArr)

    Here's how sort function work

    First, let's assume this array:

    [1,2] // where a = 1, b = 2
    

    Ascending order:

    Is a greater than b?

    If it is yes, we need to sort => return true

    Else, we don't need to sort => return false

    Descending order:

    Is a lesser than b?

    If it is yes, we need to sort => return true

    Else, we don't need to sort => return false

    In preceding example, we're verifying if a is lesser than b, then return true to sort it out else return false as this is already in descending order.


    As per @Nina Scholz

    Please do not return a Boolean value for sorting, because sort needs a value smaller than zero, zero or greater than zero. To omit equal cases may actually work, but it make for the algorithm harder to get the array to sort.

    You should consider returning 0, 1, or -1. For your case, you should use like this:

    arr.sort((a,b) => {
      if(a[2] < b[2]) return 1
      if(a[2] > b[2]) return -1
      if(a[2] === b[2]) return 0
    })
    

    Furthermore

    If the values are only integers (doesn't contain Infinity and NaN), then it can be simplifies as below,

    arr.sort((a,b) => b[2]-a[2])
    
    0 讨论(0)
  • 2021-01-28 12:09
    function bubbleSort(arr){
       var len = arr.length;
       for (var i = len-1; i>=0; i--){
         for(var j = 1; j<=i; j++){
           if(arr[j-1]<arr[j]){
               var temp = arr[j-1];
               arr[j-1] = arr[j];
               arr[j] = temp;
            }
         }
       }
       return arr;
    }
    
    console.log( bubbleSort([7,5,2,4,3,9]))
    

    console.log out put is 9 7 5 4 3 2 Modify the code to loop through your object.var in Array

    0 讨论(0)
提交回复
热议问题