javascript - 如何在Js中以函数式的方式编写代码

标签 javascript sorting

我们如何在 Javascript 中以函数式方式编写代码?

所以我最初做的是这样的

render ()  {

    if (!this.props.mainListFetching && !this.props.mainListError) {
      let testData = this.sortAmountPledgingMaximumOrMinimum(this.props.mainList, "maximum")
      console.log(testData) //Coming out to be undefined
        this.sortTypeTownOrCountry(this.props.mainList)
        this.sortPercentHighestOrLeast(this.props.mainList)

    }

这会调用以下函数

 sortPercentHighestOrLeast = (data, type) => {
       data.sort((a, b) => {
           if (type == "maximum") {
            return (
                a["percentage.funded"] - b["percentage.funded"]
            )
        } else {
            return (
                b["percentage.funded"] - a["percentage.funded"]
            )
        }
     }) 
     console.log(data)
     return data
}

我期望上述函数的结果将保存在我的 testData 变量中,但是当我 console.log 时,它是未定义的。

我的 console.log(data) 正在控制台中打印结果,确认函数正在执行并且数据不是未定义的?

[更新:]我也尝试过这个(因为 Js 是异步的)

 let testData =  this.sortAmountPledgingMaximumOrMinimum(this.props.mainList, "maximum", (data) => {
            console.log("anything") //Doesn't log anything
          })

最佳答案

假设 fundedpercentage 的嵌套属性,您可以将条件检查向前移动一步,因为您会检查每个排序迭代。

sortPercentHighestOrLeast = (data, type) => data.sort(type => type === "maximum"
    ? (a, b) => a.percentage.funded - b.percentage.funded
    : (a, b) => b.percentage.funded - a.percentage.funded
);

关于javascript - 如何在Js中以函数式的方式编写代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53243689/

相关文章:

javascript - 如何转换为 UTC?

javascript - Sort() 通过参数传递?在 JavaScript 中

java - Solr - 如何按特定字段上值的频率排序?

php - 统一排列/分布数组项

javascript - 使用 jQuery Mobile 破坏 HTML/CSS 布局

javascript - window.open 打开一个空白页

javascript - Firestore 查询,其中日期(时间戳)已超过 24 小时

JavaScript Canvas -clearImage() -canvas.getBoundingClientRect

algorithm - 需要用属性时间同步两个列表,但时间不相等

python - 使用 groupby pandas 对日期进行排序