简体   繁体   English

CoffeeScript按键对对象进行排序

[英]CoffeeScript sort array of objects by key

I'm trying to pick up some CoffeeScript but stuck on sorting an array of objects by key. 我试图拿起一些CoffeeScript,但坚持按键对对象数组进行排序。 Here's what I tried: 这是我尝试过的:

sortByKey = (array, key) ->
    array.sort( (a,b) -> a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0 )

testarr = [{i: 5, b:7}, {i:9, b:15}, {i:-4, b:-99}]
sortByKey(testarr, 'i')
val = el['b'] for el in testarr
alert val

My alert shows only -99, whereas I would have expected to see -99, 7, 15. What am I doing wrong? 我的警报仅显示-99,而我本来希望看到-99、7、15。我做错了什么?

There is no ternary operator in CoffeeScript. CoffeeScript中没有三元运算符。 Examine your compiled JavaScript and you would be able to see this immediately. 检查您编译的JavaScript,您将能够立即看到它。

You need to drop your nested ternary operators (which is a bad practice even in a language that supports them) and use an if / else : 您需要删除嵌套的三元运算符(即使在支持它们的语言中也是一种不好的做法),并使用if / else

sortByKey = (array, key) ->
  array.sort (a,b) ->
    if a[key] < b[key]
      -1
    else if a[key] > b[key]
      1
    else
      0

Next, your array comprehension is wrong. 接下来,您的数组理解是错误的。 You've done this: 您已经做到了:

a = b for b in c

That's identical to 等同于

for b in c
  a = b

Each element is assigned in turn to a , and only the final b is left in a after the loop completes. 每个元素依次分配给a ,并且在循环完成后,仅最后一个b留在a

If you want to assign the result of the comprehension itself to a variable, you need parenthesis: 如果您想将理解结果本身分配给变量,则需要括号:

a = (b for b in c)

Or, in your case 或者,就您而言

val = (el['b'] for el in testarr)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM