排序嵌套对象的数组

时间:2017-05-25 19:01:44

标签: javascript sorting

我需要对嵌套对象数组进行排序。我编写了以下代码,但由于某些原因,它将第一个元素始终放在返回的数组中,即使它不应该。

orderedArray = () => {
    let sortedArray = products
    if(this.state.interests.design && this.state.interests.code && this.state.interests.business)
        sortedArray.sort((a,b)=> (b.scores.quality-a.scores.quality))
    else if(this.state.interests.design && this.state.interests.code)
        sortedArray.sort((a,b) => (b.scores.quality*b.scores.relevancy.code*b.scores.relevancy.design/2)-(a.scores.quality*a.scores.relevancy.code*a.scores.relevancy.design/2))
    else if(this.state.interests.design && this.state.interests.business)
        sortedArray.sort((a,b) => (b.scores.quality*b.scores.relevancy.business*b.scores.relevancy.design/2)-(a.scores.quality*a.scores.relevancy.business*a.scores.relevancy.design/2))
    else if(this.state.interests.business && this.state.interests.code)
        sortedArray.sort((a,b) => (b.scores.quality*b.scores.relevancy.business*b.scores.relevancy.code/2)-(a.scores.quality*a.scores.relevancy.business*a.scores.relevancy.code/2))
    else if(this.state.interests.business)
        sortedArray.sort((a,b)=> (b.scores.quality*b.scores.relevancy.business-a.scores.quality*a.scores.relevancy.busines))
    else if(this.state.interests.code)
        sortedArray.sort((a,b)=> (b.scores.quality*b.scores.relevancy.code-a.scores.quality*a.scores.relevancy.code))
    else if(this.state.interests.design)
        sortedArray.sort((a,b)=> (b.scores.quality*b.scores.relevancy.design-a.scores.quality*a.scores.relevancy.design))
    console.log(JSON.stringify(sortedArray))
    return sortedArray
}

这个想法是,如果他们选择了设计,业务和代码,那么结果数组应该按质量排序,否则我将质量和所选变量混合在一起。这是数据:

[
    {
        "name":"dasd",
        "scores": {
            "quality": 8,
            "relevancy": {
                "design": 3,
                "code": 9,
                "business": 5
            }
        },
        {...}
    }
    {...}
]

this.state是:

    this.state = {
        minutes: int,
        interests: {
                business: bool,
                code: bool,
                design: bool
        }
    }

1 个答案:

答案 0 :(得分:1)

使用公式不能对多个属性上的数组进行排序。

鉴于一群学生"结构如In [65]: a = np.array([1.555, 2.559, 1.25-1e-10]) In [66]: a Out[66]: array([ 1.555, 2.559, 1.25 ]) In [67]: (a*100).astype(int)/100 Out[67]: array([ 1.55, 2.55, 1.24]) In [68]: (a*100+.01).astype(int)/100 Out[68]: array([ 1.55, 2.55, 1.25]) 的对象,以下不起作用:

{name:'Alice', age:8, grades:{math:12, gym:14}}

正如您在this Q/A中看到的那样,它很难在JS中实现,但有些库可以帮助实现这一点,例如下划线或lodash

使用lodash,你可以这样做:

// This does not sort by math then gym, it sorts by the result of their products, which is meaningless
students.sort((a,b) => (a.grades.math*a.grades.gym - b.grades.math*b.grades.gym))

现在适用于您的问题,而不提供完整的解决方案,这里有一个提示:

// This sorts by math score, then gym score
_.sortBy(students, [s => s.grades.math, s => s.grades.gym])