Sort array of objects by arbitrary list in JavaScript

前端 未结 2 462
旧巷少年郎
旧巷少年郎 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: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)

提交回复
热议问题