0

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', var, 7],
  ['faa', var, 3]
]

I want to sort this array from big to small using arr[2] value. Any idea how it can be done?

the desire outcome should be:

const arr = [
  ['fee', var, 7],
  ['foo', var, 5],
  ['faa', var, 3]      
]

2 Answers 2

2

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])
Sign up to request clarification or add additional context in comments.

2 Comments

please do not return a boolean value for sorting, because sort needs a value smaller than zero, zeor or greater than zero. to omit equal cases may actually work, but it make for the algorithm harder to get the array to sort.
should be arr.sort((a,b) => b[2] - a[2]). see stackoverflow.com/questions/24080785/…
0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.