最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript, array.sort() two arrays based on only one of them - Stack Overflow

programmeradmin2浏览0评论

I just discovered array.sort() and saw that I can specify how to sort like this: (example taken from .asp)

var points = [40,100,1,5,25,10];
points.sort(function(a,b){return a-b});

I've been doing my sorting manually just using Bubble Sort because the arrays are small, but I was wondering if array.sort() can be used in place of this:

// Sort rowCategories[i] by rowWidth[i]
swapped = true;
while (swapped) {
    swapped = false;
    for (var i = 0; i < rowCategories.length-1; i++) {
        if (rowWidth[i] < rowWidth[i+1]) {
            var swap = rowCategories[i];
            rowCategories[i] = rowCategories[i+1];
            rowCategories[i+1] = swap;
            swap = rowWidth[i];
            rowWidth[i] = rowWidth[i+1];
            rowWidth[i+1] = swap;
            swapped = true;
        }
    }
}

What would I write for the built in sort to do the equivalent work?

I just discovered array.sort() and saw that I can specify how to sort like this: (example taken from http://www.w3schools./jsref/jsref_sort.asp)

var points = [40,100,1,5,25,10];
points.sort(function(a,b){return a-b});

I've been doing my sorting manually just using Bubble Sort because the arrays are small, but I was wondering if array.sort() can be used in place of this:

// Sort rowCategories[i] by rowWidth[i]
swapped = true;
while (swapped) {
    swapped = false;
    for (var i = 0; i < rowCategories.length-1; i++) {
        if (rowWidth[i] < rowWidth[i+1]) {
            var swap = rowCategories[i];
            rowCategories[i] = rowCategories[i+1];
            rowCategories[i+1] = swap;
            swap = rowWidth[i];
            rowWidth[i] = rowWidth[i+1];
            rowWidth[i+1] = swap;
            swapped = true;
        }
    }
}

What would I write for the built in sort to do the equivalent work?

Share Improve this question asked Jul 2, 2013 at 1:37 asimesasimes 6,1465 gold badges45 silver badges80 bronze badges 5
  • 1 You may sort an array of objects instead... (and w3school isn't very good. For reference you may want to see Array.sort on MDN instead) – Alvin Wong Commented Jul 2, 2013 at 1:42
  • I agree, if you store both values in one object then you can simply use sort. – rsbarro Commented Jul 2, 2013 at 1:44
  • rowCategories[] is an array of objects (I think of it as a class), so I should make rowWidth[] part of it? – asimes Commented Jul 2, 2013 at 1:46
  • Yes, just add a width: property to each element. – Barmar Commented Jul 2, 2013 at 1:47
  • Yes, I would use that approach if possible. – rsbarro Commented Jul 2, 2013 at 1:47
Add a ment  | 

4 Answers 4

Reset to default 2

There is a way of multi sorting arrays but I like the array of objects better. Here is the multi sort:

function multisort(sortBy,otherArrays){
  var keys=[],i,tmpKeys;
  sortBy.sort(function(a,b){
    var ret=(a>b)?1:(a<b)?-1:0;
    // storing the return values to be used for the other arrays
    keys.push(ret);
    return ret;
  });
  for(i=0;i<otherArrays.length;i++){
    // copy the stored retun values
    tmpKeys=keys.concat([]);
    otherArrays[i].sort(function(){
      // return the saved values based on sortBy array's sort
      return tmpKeys.splice(0,1);
    });
  }
}

var arr1=[1,2,3],
arr2=[5,6,7],
reverse=["c","b","a"];
multisort(reverse,[arr1,arr2])
console.log(arr1);
console.log(arr2);
console.log(reverse);

Sorting by object key:

var arr=[
  {id:1,col1:3,col2:2},
  {id:2,col1:2,col2:2},
  {id:3,col1:1,col2:1}
];

function sortBy(arr,keys){
  var i=0;
  arr.sort(function(a,b){
    var i=0;
    while(a[keys[i]]===b[keys[i]]&&i<keys.length){
      i++;
    }
    return (keys.length===i)?0:(a[keys[i]]>b[keys[i]])?1:-1;
  });
}
//sort by col2 then col1
sortBy(arr,["col2","col1"]);
console.log(arr);
//sort by id
sortBy(arr,["id"]);
console.log(arr);

this only requires a little modification. Instead of storing two arrays store one array with an object with the two attributes. Then you can do something like this.

arr.sort(functiona(a,b){return a.rowWidth - b.rowWidth});

the object must contain the attributes rowWidth and rowCatagories

The built-in sort() can only sort one array at a time, and the parison is based on the values, not the indexes.

What you're doing is similar to PHP's array_multisort() function. If you use load the php.js library, it includes an implementation of this function. The implementation is here.

Actually the vanilla the sort function uses depends on browser JS engine implementation, for instance Mozilla uses MergeSort I believe.

By default it pare array items as strings and if you need any other consideration you must pass your own pare function to sort and function must return negative, 0 or positive number indicating the items parison result.

You can use this sort function instead of yours, that would be much faster.

发布评论

评论列表(0)

  1. 暂无评论