首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用JQuery按多个属性对对象数组进行排序

使用JQuery按多个属性对对象数组进行排序
EN

Stack Overflow用户
提问于 2017-09-15 17:32:46
回答 1查看 117关注 0票数 0

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

代码语言:javascript
运行
复制
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"},
];

这里的输出将是:

代码语言:javascript
运行
复制
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):

代码语言:javascript
运行
复制
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属性。

EN

回答 1

Stack Overflow用户

发布于 2017-09-15 19:58:36

@LeonidasFett,我这里有一个javascript逻辑,首先按年份排序。在按类型排序之前,您可以在您的反应中即兴发挥这一点。

代码语言:javascript
运行
复制
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记录到控制台将是:

代码语言:javascript
运行
复制
[ 
 {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"}
]

然后按类型排序。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46236347

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档