-
暮色呼如
示例如下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` hereconst 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;}// Useconsole.log(getClass('tenth'));
-
慕沐林林
这是你想要的: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()]);
-
RISEBY
数组.prototype.reduceconst 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));
-
LEATH
你可以用forEach我用过rank的key代替classvar 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)
-
holdtom
您可以尝试使用下一个功能。抱歉格式化无法在手机上工作..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"));