计算数组中相同元素的个数

如下面的数组, 希望得到[{name: 'zhang', conut: 4},{name: 'wang', conut: 2},{name: 'liu', conut: 2}],或者[{zhang: 4},{wang: 2},{liu: 2}]谢谢了

let arr= [
            {name: 'zhang', age: '20'},
            {name: 'wang', age: '22'},
            {name: 'zhang', age: '20'},
            {name: 'liu', age: '23'},
            {name: 'liu', age: '23'},
            {name: 'wang', age: '22'},
            {name: 'zhang', age: '20'},
            {name: 'zhang', age: '20'},
        ]
阅读 4.3k
6 个回答
const obj = {};
arr.forEach(i => {
    if(obj[i.name]) {
        obj[i.name].count += 1;
    } else {
        obj[i.name] = {
            name: i.name,
            count: 1
        }
    }
});

const result = Object.keys(obj).map(name => obj[name]);
<script>
    let arr= [
            {name: 'zhang', age: '20'},
            {name: 'wang', age: '22'},
            {name: 'zhang', age: '20'},
            {name: 'liu', age: '23'},
            {name: 'liu', age: '23'},
            {name: 'wang', age: '22'},
            {name: 'zhang', age: '20'},
            {name: 'zhang', age: '20'},
    ]
    var map = {},
        newList = [];
    for (var i = 0; i < arr.length; i++) {
      var obj = arr[i];
      if (!map[obj.name]) {
        newList.push({
          name: obj.name,
          count: 1
        });
        map[obj.name] = obj;
      } else {
        for (var j = 0; j < newList.length; j++) {
          if (newList[j].name == obj.name) {
            newList[j].count++;
            break;
          }
        }
      }
    }
    console.log("新数组", newList)

</script>
var _obj = {},_arr = [];
[
    {name: 'zhang', age: '20'},
    {name: 'wang', age: '22'},
    {name: 'zhang', age: '20'},
    {name: 'liu', age: '23'},
    {name: 'liu', age: '23'},
    {name: 'wang', age: '22'},
    {name: 'zhang', age: '20'},
    {name: 'zhang', age: '20'},
].forEach((v)=>{
    if(_obj[v.name]){
        _obj[v.name]++
    }else{
        _obj[v.name]=1
    }
})
Object.keys(_obj).map(v=>({name:v,count:_obj[v]}))

clipboard.png

let arr = [
  {name: 'zhang', age: '20'},
  {name: 'wang', age: '22'},
  {name: 'zhang', age: '20'},
  {name: 'liu', age: '23'},
  {name: 'liu', age: '23'},
  {name: 'wang', age: '22'},
  {name: 'zhang', age: '20'},
  {name: 'zhang', age: '20'},
];

const result = arr.reduce((list, o) => {
  const item = list.find(n => n.name === o.name && n.age === o.age);
  !item ? list.push({...o, count: 1}) : item.count += 1;
  return list;
}, []);

console.log(result)
// 第一步生成一个统计过的对象
const allNames = arr.reduce((all, next, index) => {
  if (next.name in all) {
    all[next.name]  ++ 
  } else {
    all[next.name] = 1
  }
  return all
}, {})
let newArr = []
// 第二部把对象push到数组中
for (const key in allNames) {
  if (allNames.hasOwnProperty(key)) {
    let currentObj = {}
    currentObj[key] = allNames[key]
    newArr.push(currentObj)
  }
}
console.log(newArr)

clipboard.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏