简体   繁体   中英

Sort through array of n-dimensional objects in javascript

I am trying to sort through arrays of n-dimensional objects based on a certain index. For example if I have an array:

var array1 = [['c',24,"John"],['a',-13,"Cindy"],['b',98,"Alex"]];

I want to be able to sort by any dimension. Does anything exist in javascript that would give me outputs that look like the following?

array1.sort(sortFunction(0));
- [['a',-13,"Cindy"],['b',98,"Alex"],['c',24,"John"]]

array1.sort(sortFunction(1));
- [['a',-13,"Cindy"],['c',24,"John"],['b',98,"Alex"]]

array1.sort(sortFunction(2));
- [['b',98,"Alex"],['a',-13,"Cindy"],['c',24,"John"]]

Thanks!

To clarify: I am aware you must write a sort function, but can you write one that takes in an argument? Here would be an example:

function sortFunction(dim){
  if (a[dim] === b[dim]) {
    return 0;
  }
  else {
    return (a[dim] < b[dim]) ? -1 : 1;
  }
}

You can write a function generator that take the index of the parameters in your array :

var array = [['a',24,"John"],['a',-13,"Cindy"],['b',98,"Alex"]];

  function sorting(index) {
    return function(a, b) {
        return a[index] < b[index]?-1:(a[index] > b[index])?1:0;
    }
  }

  var res1 = array.sort(sorting(0));
  var res2 = array.sort(sorting(1));
  var res3 = array.sort(sorting(2));

Note: this is the basic approach of how the sort callback function works. For a more elegant solution see Paul Boute's answer . His solution is especially useful when the function needs to be applied in more than one situation.


Your sort function needs to compare two properties of the elements (or the two elements) themselves. It needs to return a negative number if they are in the correct order, 0 if they are equivalent and a positive number if they are in the wrong order.

A JavaScript example of such a function:

function sortFunction(elementA,elementB,index){
  if(elementA[index]<elementB[index]){
    return -1;
  }
  else if(elementA[index]>elementB[index]){
    return 1;
  }
  else{
    return 0;
  }
}

Invokable as such:

array1.sort(function(a,b){
  return sortFunction(a,b,1);
});

Or the shorter all-in-one version:

array1.sort(function(a,b){
  var index=1;
  if(a[index]<b[index]){
    return -1;
  }
  else if(a[index]>b[index]){
    return 1;
  }
  else{
    return 0;
  }
});

You can also use a library like underscore.js . Then, simply

// which index to sort on
var s = 1;
// sort it - it will work for objects too
_.sortBy(array1, function(a){ return a[s];});

// or simply use "property name" to sort on
_.sortBy( array1, s);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM