JavaScript-计算并删除对象ES6数组中的重复项 [英] JavaScript - Count and remove duplicates from array of objects ES6

查看:31
本文介绍了JavaScript-计算并删除对象ES6数组中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上是在寻找一种简洁简洁的解决方案(可能使用ES6),以减少重复对象的数组并计算重复的数量.

I am basically looking for a neat and succinct solution (possibly using ES6) for reducing an array of duplicate objects and counting the quantity of duplicates.

例如

const items = [
   {
     id: 1,
     type: 'PEPSI',
   },
  {
     id: 1,
     type: 'PEPSI',
   },
  {
     id: 1,
     type: '7UP',
   },
  {
     id: 1,
     type: 'FANTA',
   },
  {
     id: 2,
     type: 'FANTA',
   },
  {
     id: 2,
     type: '7UP',
   },
  {
     id: 2,
     type: '7UP',
   }
];

function getItems(data, id) {
      return data.filter(x => x.id === id).map((item) => {
        const obj = {};
        obj.quantity = **I want the quantity to go here**
        obj.type = item.type;
        return obj;
      });
    }

因此,运行功能 getItems(items,1)会给我:

So running the function getItems(items, 1) would give me:

[
 { quantity: 2, type: 'PEPSI' },
 { quantity: 1, type: '7UP' },
 { quantity: 1, type: 'FANTA' }
]

提前谢谢!

推荐答案

您可以使用以下代码:

const items = [
   {
     id: 1,
     type: 'PEPSI',
   },
  {
     id: 1,
     type: 'PEPSI',
   },
  {
     id: 1,
     type: '7UP',
   },
  {
     id: 1,
     type: 'FANTA',
   },
  {
     id: 2,
     type: 'FANTA',
   },
  {
     id: 2,
     type: '7UP',
   },
  {
     id: 2,
     type: '7UP',
   }
];

const getItems = (data) => {
    return data.reduce((a,b) => {
        const item = a.find(i => i.type === b.type);
        if(item){
            item.quantity = item.quantity + 1;
        }
        else {
            a.push({
                quantity: 0,
                type: b.type
            });
        }
        return a;
    }, []);
};
console.log(getItems(items));

const getItemsWithId = (data, id) => {
return data.reduce((a,b) => {
    if(b.id === id) {
        const item = a.find(i => i.type === b.type);
        if(item){
            item.quantity = item.quantity + 1;
        }
        else {
            a.push({
                quantity: 0,
                type: b.type
            });
        }   
    }
    return a;
}, []);
};

console.log(getItemsWithId(items, 1));

这篇关于JavaScript-计算并删除对象ES6数组中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆