按关联顺序排序

时间:2018-04-06 18:15:15

标签: javascript arrays sorting

如何按年龄按升序对此数组进行排序

var employ = [
    {"id":1, "name":"Andrew", "age":30, "gender":"m", "category":"G"},
    {"id":2, "name":"Brandon", "age":25, "gender":"m", "category":"G"},
    {"id":3, "name":"Christine", "age":20, "gender":"m", "category":"G"},
    {"id":4, "name":"Elena", "age":29, "gender":"W", "category":"M"}   
    ];`

所需的输出是:

var employ = [
{"id":3, "name":"Christine", "age":20, "gender":"m", "category":"G"},
{"id":2, "name":"Brandon", "age":25, "gender":"m", "category":"G"},
{"id":4, "name":"Elena", "age":29, "gender":"W", "category":"M"},
{"id":1, "name":"Andrew", "age":30, "gender":"m", "category":"G"}
        ];

我尝试使用 employ.sort(),但我没有获得所需的输出。

1 个答案:

答案 0 :(得分:0)

您可以先获得最大年龄,然后按年龄过滤,choice是否包含所需值。



var employ = [{ id: 1, name: "Andrew", age: 30, gender: "m", category: "G", choice: ["A", "C", "D", "B", "E"] }, { id: 2, name: "Brandon", age: 25, gender: "m", category: "G", choice: ["A", "C", "D", "E", "B"] }, { id: 3, name: "Christine", age: 20, gender: "m", category: "G", choice: ["A", "E", "D", "B", "C"] }, { id: 4, name: "Elena", age: 29, gender: "W", category: "M", choice: ["E", "C", "D", "A", "B"] }],
    maxAge = Math.max(...employ.map(({ age }) => age)),
    result = employ.filter(({ age, choice }) => age === maxAge && choice.includes('A'));

console.log(result);

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