【发布时间】:2020-06-26 19:03:38
【问题描述】:
我想创建一个按特定键的值对数组进行排序的函数。
我会举个例子。
[{ text: 'hi', author: 'Boy' },
{ text: 'how are you', author: 'Boy' },
{ text: 'I\'m good', author: 'Boy' },
{ text: 'hello', author: 'Girl' },
{ text: 'Bye', author: 'Boy' }]
在上面的数组中,'Girl' author 比 'Boy' author 多,所以它应该返回以下数组
[{ text: 'hello', author: 'Girl' },
{ text: 'hi', author: 'Boy' },
{ text: 'how are you', author: 'Boy' },
{ text: 'I\'m good', author: 'Boy' },
{ text: 'Bye', author: 'Boy' }]
第二个例子:
[{ text: 'hi', author: 'Boy' },
{ text: 'hola', author: 'Mom' },
{ text: 'how are you', author: 'Boy' },
{ text: 'I\'m good', author: 'Boy' },
{ text: 'hello', author: 'Girl' },
{ text: 'eat this', author: 'Mom' },
{ text: 'Bye', author: 'Boy' }]
第二个结果:
[{ text: 'hello', author: 'Girl' },
{ text: 'hola', author: 'Mom' },
{ text: 'eat this', author: 'Mom' },
{ text: 'hi', author: 'Boy' },
{ text: 'how are you', author: 'Boy' },
{ text: 'I\'m good', author: 'Boy' },
{ text: 'Bye', author: 'Boy' }]
最后一个例子:
const data = [
{ text: 'hi', author: 'Boy' },
{ text: 'hola', author: 'Mom' },
{ text: 'hola', author: 'Mom' },
{ text: 'hola', author: 'Mom' },
{ text: 'how are you', author: 'Boy' },
{ text: "I'm good", author: 'Boy' },
{ text: 'hello', author: 'Girl' },
{ text: 'eat this', author: 'Mom' },
{ text: 'Bye', author: 'Boy' }
]
最后的结果(我不在乎男孩是第一个还是妈妈是第一个
const data = [
{ text: 'hello', author: 'Girl' },
{ text: 'hola', author: 'Mom' },
{ text: 'hola', author: 'Mom' },
{ text: 'hola', author: 'Mom' },
{ text: 'eat this', author: 'Mom' },
{ text: 'hi', author: 'Boy' },
{ text: 'how are you', author: 'Boy' },
{ text: "I'm good", author: 'Boy' },
{ text: 'Bye', author: 'Boy' }
]
【问题讨论】:
-
您要按作者数排序吗?
-
你能澄清一下吗?这个输入的输出是什么 `[{ text: 'hi', author: 'Boy' }, { text: 'hola', author: 'Mom' }, { text: 'how are you', author: '男孩' }, { 文字:'吃这个',作者:'妈妈' }
-
@shilu 那么如果作者数量相同呢?
-
@shilu 好的,请查看我对您帖子的回答。
标签: javascript arrays node.js sorting object