我需要根据数组中值的流行程度对字符串数组进行排序



我有一个字符串数组,其中一些值是这样的多次。

const arr = ['banana', 'orange', 'banana', 'apple', 'apple', 'apple', 'orange', 'apple', 'banana']

最后,我想得到一个对象数组,其中最流行的值首先与数组中的值配对,依此类推:

const newArr = [
{ fruit: 'apple', count: 4 },
{ fruit: 'banana', count: 3 }, 
{ fruit: 'orange', count: 2 } 
]

简单地使用reduce函数将水果列表缩减为带计数的对象就足够了

const arr = ['banana', 'orange', 'banana', 'apple', 'apple', 'apple', 'orange', 'apple', 'banana']
const partialResult = arr.reduce((result, fruit) => {
if (!result[fruit]) result[fruit] = 1;
else result[fruit]+=1;

return result;
}, {});
const result = Object.entries(partialResult).map(([fruit, count]) => ({fruit, count})).sort(({count: countA},{count: countB})=> countB-countA);
console.log(result);

使用临时对象:

const dict = {}
const newArr = []
arr.forEach(v => {
if (!dict[v]) {
dict[v] = {fruit: v, count:0}
newArr.push(dict[v])
}
dict[v].count++
})
newArr.sort((o1, o2) => o2.count - o1.count)

您可以使用find检查元素是否已包含在newArr中;如果只是更新计数,如果不是推送新对象。最后对newArry:进行排序

const arr = ['banana', 'orange', 'banana', 'apple', 'apple', 'apple', 'orange', 'apple', 'banana']
const newArr = [];
arr.forEach(fruit => {
let obj = newArr.find(a => a.fruit === fruit);
if(obj) obj.count++;
else    newArr.push({fruit: fruit, count: 1});
});
newArr.sort( (a, b) => b.count - a.count);
console.log(newArr);

最新更新