要求是获取对象数组中每个“用户”的前X个score
。
对象数组已按用户,得分进行排序。
例如,如果它是我们之后的“前3个”,并且用户“ barney”的数组中有4行-然后从用户数组中返回前3个元素 “巴尼”。
另一个例子:如果它是我们排在后面的“前3名”,并且用户在数组中有2个元素,则返回这2个元素。
这是我想要TOP 3的示例:
var users = [
{ user: 'barney', score: 39},
{ user: 'barney', score: 37},
{ user: 'barney', score: 36},
{ user: 'barney', score: 36},
{ user: 'fred', score: 40},
{ user: 'fred', score: 22},
{ user: 'wilma', score: 40},
{ user: 'wilma', score: 40}
];
因此在此示例中,结果应为:
[
{ user: 'barney', score: 39},
{ user: 'barney', score: 37},
{ user: 'barney', score: 36},
{ user: 'fred', score: 40},
{ user: 'fred', score: 22},
{ user: 'wilma', score: 40},
{ user: 'wilma', score: 40}
];
答案 0 :(得分:1)
没有lodash也有可能,所以有了lodash也有可能。
按用户拆分原始数组,使用slice保留第一个x,将所有内容合并回1个数组。
var users = [
{ user: 'barney', score: 39},
{ user: 'barney', score: 37},
{ user: 'barney', score: 36},
{ user: 'barney', score: 36},
{ user: 'fred', score: 40},
{ user: 'fred', score: 22},
{ user: 'wilma', score: 40},
{ user: 'wilma', score: 40}
];
var x = 3;
var names = users.reduce((acc, n) => {
acc.add(n.user);
return acc;
}, new Set());
var groups = [...names].reduce((acc, n) => {
acc.push(users.filter(m => m.user === n));
return acc;
}, []);
groups = groups.map(n => n.slice(0, x));
var result = groups.reduce((acc, n) => {
acc.push(...n);
return acc;
}, []);
console.log(result);
答案 1 :(得分:1)
假设const getTop = (users, top, counts = {}) =>
users.filter(({ user }) => (counts[user] = (counts[user] || 0) + 1) <= top);
集合已经按名称和分数排序,则可以简单地通过使用Array#filter来实现。
var users = [
{ user: 'barney', score: 39},
{ user: 'barney', score: 37},
{ user: 'barney', score: 36},
{ user: 'barney', score: 36},
{ user: 'fred', score: 40},
{ user: 'fred', score: 22},
{ user: 'wilma', score: 40},
{ user: 'wilma', score: 40}
];
const getTop = (users, top, counts = {}) =>
users.filter(({ user }) => (counts[user] = (counts[user] || 0) + 1) <= top);
console.log('TOP 1', getTop(users, 1));
console.log('TOP 2', getTop(users, 2));
console.log('TOP 3', getTop(users, 3));
.as-console-wrapper{min-height:100%;}
char