gpt4 book ai didi

javascript - 按对象值的数组位置

转载 作者:行者123 更新时间:2023-12-02 21:27:52 25 4
gpt4 key购买 nike

我想创建一个按特定键的值对数组进行排序的函数。

我举个例子。

[{ text: 'hi', author: 'Boy' },
{ text: 'how are you', author: 'Boy' },
{ text: 'I\'m good', author: 'Boy' },
{ text: 'hello', author: 'Girl' },
{ text: 'Bye', author: 'Boy' }]

在上面的数组中,“女孩”作者多于“男孩”作者,因此它应该返回以下数组

[{ 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' }
]

最佳答案

如果您修改数据集并向其添加计数,则以下代码应该可以完成这项工作。

var data = [{ 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' }];

// add counts against each object
data.forEach(obj => {
obj['count'] = data.filter((obj1) => obj1.author ===
obj.author).length;
})

// user Array.sort function to sort your data
data.sort(function(a, b){
if(a.count < b.count) return -1;
if(a.count > b.count) return 1;
return 0;
});

不过,如果您从后端对这个列表进行排序,那就更好了。

关于javascript - 按对象值的数组位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60692904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com