为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

萧十郎 2022-12-02 16:47:42
我有一个数组const arr = [{    name:'john',    class:'tenth'},{    name:'josh',    class:'ninth'},{    name:'ajay',    class:'tenth'}]如何找出数组中第九次和第十次出现的次数。但是通过使用单个函数,我可以获得每个班级学生的数据并在我的页面加载时显示。例如。:X- 2IX- 1 XII- 9ETC
查看完整描述

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'));


查看完整回答
反对 回复 2022-12-02
?
慕沐林林

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()]);


查看完整回答
反对 回复 2022-12-02
?
RISEBY

TA贡献1856条经验 获得超5个赞

数组.prototype.reduce

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));


查看完整回答
反对 回复 2022-12-02
?
LEATH

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)


查看完整回答
反对 回复 2022-12-02
?
holdtom

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"));


查看完整回答
反对 回复 2022-12-02
  • 5 回答
  • 0 关注
  • 121 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信