Sort array of objects by arbitrary list in JavaScript

前端 未结 2 439
旧巷少年郎
旧巷少年郎 2021-01-04 09:58

Given an array of objects like this:

objects = [
  { id: \'aaaa\', description: \'foo\' },
  { id: \'bbbb\', description: \'bar\' },
  { id: \'cccc\', descri         


        
相关标签:
2条回答
  • 2021-01-04 10:18

    You need a way to translate the string into the position in the array, i.e. an index-of function for an array.

    There is one in newer browsers, but to be backwards compatible you need to add it if it's not there:

    if (!Array.prototype.indexOf) {
      Array.prototype.indexOf = function(str) {
        var i;
        for (i = 0; i < this.length; i++) if (this[i] == str) return i;
        return -1;
      }
    }
    

    Now you can sort the array by turning the string into an index:

    objects.sort(function(x,y){ return order.indexOf(x.id) - order.indexOf(y.id); });
    

    Demo: http://jsfiddle.net/Guffa/u3CQW/

    0 讨论(0)
  • 2021-01-04 10:21

    Try this:

    objects.sort(function(a, b){
        return order.indexOf(a.id) - order.indexOf(b.id)
    });
    

    Assuming the variables are like you declared them in the question, this should return:

    [
        { id: 'bbbb', description: 'bar' },
        { id: 'aaaa', description: 'foo' },
        { id: 'cccc', description: 'baz' }
    ];
    

    (It actually modifies the objects variable)

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