查找对象属性值在数组中出现的次数

我有一个数组


const arr = [{

    name:'john',

    class:'tenth'

},

{

    name:'josh',

    class:'ninth'

},

{

    name:'ajay',

    class:'tenth'

}]

如何找出数组中第九次和第十次出现的次数。但是通过使用单个函数,我可以获得每个班级学生的数据并在我的页面加载时显示。


例如。:


X- 2

IX- 1 

XII- 9

ETC


萧十郎
浏览 191回答 5
5回答

暮色呼如

示例如下const arr = [&nbsp; {&nbsp; &nbsp; name:'john',&nbsp; &nbsp; class:'tenth'&nbsp; },&nbsp; {&nbsp; &nbsp; name:'josh',&nbsp; &nbsp; class:'ninth'&nbsp; },&nbsp; {&nbsp; &nbsp; name:'ajay',&nbsp; &nbsp; class:'tenth'&nbsp; }];// Create function to return number of matched classes// *** We can't use word `class` as function parameter,// so we use `cls` hereconst getClass = (cls) => {&nbsp; // Match var&nbsp; let mTimes = 0;&nbsp; // Loop arr&nbsp; for(let i = 0; i < arr.length; i++) {&nbsp; &nbsp; // If matches request, count&nbsp; &nbsp; if(arr[i].class === cls) mTimes++;&nbsp; }&nbsp; return mTimes;}// Useconsole.log(getClass('tenth'));

慕沐林林

这是你想要的:const arr = [{&nbsp; &nbsp; name: 'john',&nbsp; &nbsp; class: 'tenth'},{&nbsp; &nbsp; name: 'josh',&nbsp; &nbsp; class: 'ninth'},{&nbsp; &nbsp; name: 'ajay',&nbsp; &nbsp; class: 'tenth'}];console.log([...arr.reduce((a, c) => {&nbsp; &nbsp; if (a.has(c.class)) {&nbsp; &nbsp; &nbsp; &nbsp; a.get(c.class).count++;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; a.set(c.class, { class: c.class, count: 1 });&nbsp; &nbsp; }&nbsp; &nbsp; return a;}, new Map()).values()]);

RISEBY

数组.prototype.reduceconst arr = [{&nbsp; &nbsp; name: 'john',&nbsp; &nbsp; className: 'tenth'&nbsp; },&nbsp; {&nbsp; &nbsp; name: 'josh',&nbsp; &nbsp; className: 'ninth'&nbsp; },&nbsp; {&nbsp; &nbsp; name: 'ajay',&nbsp; &nbsp; className: 'tenth'&nbsp; }]function groupByClassName(arr) {&nbsp; return arr.reduce((cum, cur) => {&nbsp; &nbsp; if(!cum[cur.className]) cum[cur.className] = 0;&nbsp; &nbsp; cum[cur.className]++;&nbsp; &nbsp; return cum;&nbsp; }, {})}console.log(groupByClassName(arr));

LEATH

你可以用forEach我用过rank的key代替classvar g={}var count = 1&nbsp;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' }, ]&nbsp; arrx.forEach(o => {&nbsp; &nbsp; g[o.rank] = g[o.rank]||count&nbsp; &nbsp; g[o.rank] = count++&nbsp; })&nbsp; console.log(g)

holdtom

您可以尝试使用下一个功能。抱歉格式化无法在手机上工作..Function groupBy(arr, prop) {&nbsp; &nbsp;const map = new Map(Array.from(arr, obj => [obj[prop], []]));}&nbsp;arr.forEach(obj => map.get(obj[prop]).push(obj));&nbsp; &nbsp; return Array.from(map.values());}&nbsp; &nbsp;&nbsp;console.log(groupBy(data, "class"));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript