2017-08-02 83 views
-3

我有一个SortableList,您可以在其中组织您的订单以制定过滤器优先级。按优先级排序数据

这样的:

[ 
    0: "Fruits", 
    1: "Legumes", 
    2: "Example1", 
] 

然后我有一些数据是这样的:

[ 
    { 
     id: 0, 
     _source: { 
        someOtherProps, 
        source: "Fruits" 
       } 
    }, 
    { 
     id: 1, 
     _source: { 
        someOtherProps, 
        source: "Example1" 
       } 
    }, 
    .... blablabla 
] 

我想通过源对数据进行排序,尊重秩序的优先事项。

我尝试使用sort()函数,但我没有任何想法如何做到这一点。

在这个例子中:我将所有的数据对象首先由源“Fruits”排序,然后是“豆类”,然后是“Example1”。

+1

*“我尝试用sort()函数,但我没有任何想法如何,我能做到这一点。” * ** **显示你尝试过什么。如果你没有成功地尝试任何事情,那么做更多的研究。 –

回答

1

您可以使用一个对象作为排序顺序,并将delta作为回调的结果。

var order = { Fruits: 1, Legumes: 2, Example1: 3 }, 
 
    data = [{ id: 0, _source: { source: "Fruits" } }, { id: 1, _source: { source: "Example1" } }]; 
 
    
 
data.sort((a, b) => order[a._source.source] - order[b._source.source]); 
 

 
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }