5 回答
TA贡献1853条经验 获得超9个赞
示例如下
const arr = [
{
name:'john',
class:'tenth'
},
{
name:'josh',
class:'ninth'
},
{
name:'ajay',
class:'tenth'
}
];
// Create function to return number of matched classes
// *** We can't use word `class` as function parameter,
// so we use `cls` here
const getClass = (cls) => {
// Match var
let mTimes = 0;
// Loop arr
for(let i = 0; i < arr.length; i++) {
// If matches request, count
if(arr[i].class === cls) mTimes++;
}
return mTimes;
}
// Use
console.log(getClass('tenth'));
TA贡献2016条经验 获得超9个赞
这是你想要的:
const arr = [{
name: 'john',
class: 'tenth'
},
{
name: 'josh',
class: 'ninth'
},
{
name: 'ajay',
class: 'tenth'
}
];
console.log([...arr.reduce((a, c) => {
if (a.has(c.class)) {
a.get(c.class).count++;
} else {
a.set(c.class, { class: c.class, count: 1 });
}
return a;
}, new Map()).values()]);
TA贡献1856条经验 获得超5个赞
const arr = [{
name: 'john',
className: 'tenth'
},
{
name: 'josh',
className: 'ninth'
},
{
name: 'ajay',
className: 'tenth'
}
]
function groupByClassName(arr) {
return arr.reduce((cum, cur) => {
if(!cum[cur.className]) cum[cur.className] = 0;
cum[cur.className]++;
return cum;
}, {})
}
console.log(groupByClassName(arr));
TA贡献1936条经验 获得超6个赞
你可以用forEach我用过rank的key代替class
var g={}
var count = 1
const arrx = [{ name:'john',rank:'tenth' }, { name:'josh', rank:'ninth' }, { name:'ajay', rank:'tenth' }, { name:'steph', rank:'tenth' }, { name:'nick', rank:'tenth' }, { name:'ajay', rank:'ninth' }, { name:'ajay', rank:'ninth' }, ]
arrx.forEach(o => {
g[o.rank] = g[o.rank]||count
g[o.rank] = count++
})
console.log(g)
TA贡献1805条经验 获得超10个赞
您可以尝试使用下一个功能。抱歉格式化无法在手机上工作..
Function groupBy(arr, prop) {
const map = new Map(Array.from(arr, obj => [obj[prop], []]));
}
arr.forEach(obj => map.get(obj[prop]).push(obj));
return Array.from(map.values());
}
console.log(groupBy(data, "class"));
添加回答
举报