使用JQuery

时间:2017-09-15 09:32:46

标签: jquery sorting

我如何对以下数组进行排序,以便它首先按年度跨度和每年跨度应用排序,它首先按“简单”类型然后“复杂”进行排序?我还需要数组中每个排序的起始索引和计数。所以在这种情况下。问题是阵列可以是动态的,这意味着可以添加新年跨度。

var array = [
    {"name":"one", "year":"2017-2018", "type":"simple"},
    {"name":"two", "year":"2018-2019", "type":"complex"},
    {"name":"three", "year":"2017-2018", "type":"complex"},
    {"name":"four", "year":"2018-2019", "type":"complex"},
    {"name":"five", "year":"2018-2019", "type":"simple"},
    {"name":"six", "year":"2017-2018", "type":"simple"},
];

这里的输出是:

var array = [
    {"name":"one", "year":"2017-2018", "type":"simple"},
    {"name":"six", "year":"2017-2018", "type":"simple"},
    {"name":"three", "year":"2017-2018", "type":"complex"},
    {"name":"five", "year":"2018-2019", "type":"simple"},
    {"name":"two", "year":"2018-2019", "type":"complex"},
    {"name":"four", "year":"2018-2019", "type":"complex"},
];

//These need to be generated dynamically
startIndex2017simple = 0;
count2017simple = 2;
startIndex2017complex = 2;
count2017complex = 1;
startIndex2018simple = 3;
count2018simple = 1;
startIndex2018complex = 4;
count2018complex = 2;

到目前为止,我只是按照简单或复杂的方式进行排序,而不是按年份排序。

这是我当前的代码(TypeScript和React):

props.items.forEach((item, index) => {
    if(item.type=== "simple")
        sorted.unshift(item);
    else
        sorted.push(item);
});

this.simples = props.items.filter((item)=>{
    return item.type === "simple"
});
this.complex= props.items.filter((item)=>{
    return item.type !== "complex"
});      

我通过使用简单和复杂数组获得startIndex和count属性。

1 个答案:

答案 0 :(得分:1)

@LeonidasFett,我这里有一个javascript逻辑,首先按年排序。在按类型排序之前,您可以将其即兴创作到您的React中。

var testArray = [
    {"name":"one", "year":"2017-2018", "type":"simple"},
    {"name":"two", "year":"2018-2019", "type":"complex"},
    {"name":"three", "year":"2017-2018", "type":"complex"},
    {"name":"four", "year":"2018-2019", "type":"complex"},
    {"name":"five", "year":"2018-2019", "type":"simple"},
    {"name":"six", "year":"2017-2018", "type":"simple"}
];

testArray.sort(function(a, b) {
    return a.year.substring(0, 4) - b.year.substring(0, 4);
});

将testArray记录到控制台现在将是:

[ 
 {name: "one", year: "2017-2018", type: "simple"}, 
 {name: "three", year: "2017-2018", type: "complex"}, 
 {name: "six", year: "2017-2018", type: "simple"},
 {name: "two", year: "2018-2019", type: "complex"},
 {name: "four", year: "2018-2019", type: "complex"},
 {name: "five", year: "2018-2019", type: "simple"}
]

然后按类型排序。