汇总JavaScript集合

时间:2020-11-12 06:33:30

标签: javascript arrays collections

我有一个集合,在其中必须仅使用javascript使用聚合。我已经尝试过使用Lodash库做一些事情,但是没有运气。如果您可以通过某种方式指导我对收藏进行分组,” 我认为应该解决。

var sample = [
        {
           

            "DESCRIPTOR": "HAPPY",
            "DESCRIPTOR_ID": 400001,
            "QUESTION_ID": "A_QUES_1",
            "CHOICE": "A",
            "SCORE": 1,
            "__v": 0
        },
        {
           

            "DESCRIPTOR": "HAPPY",
            "DESCRIPTOR_ID": 400001,
            "QUESTION_ID": "A_QUES_2",
            "CHOICE": "B",
            "SCORE": 2,
            "__v": 0
        },
{
           

            "DESCRIPTOR": "SAD",
            "DESCRIPTOR_ID": 400002,
            "QUESTION_ID": "B_QUES_1",
            "CHOICE": "A",
            "SCORE": 2,
            "__v": 0
        },
        {
           

            "DESCRIPTOR": "SAD",
            "DESCRIPTOR_ID": 400002,
            "QUESTION_ID": "B_QUES_2",
            "CHOICE": "B",
            "SCORE": 2,
            "__v": 0
        }
    ]

我希望像下面这样,

 result = [{"DESCRIPTOR": "HAPPY", "TOTAL_SCORE":3}, {"DESCRIPTOR": "SAD", "TOTAL_SCORE":4}]

您能帮我只用Java编写此代码吗? 谢谢

2 个答案:

答案 0 :(得分:0)

您可以为此使用数组reduce方法,

let result = sample.reduce((prev, curr) => {
   const descriptorName = curr.DESCRIPTOR;
   const index = prev.findIndex((item) => item.DESCRIPTOR === descriptorName);
   if(index > -1) {
      prev[index].SCORE += curr.SCORE;
   } else {
      prev.push({'DESCRIPTOR': descriptorName, 'SCORE': curr.SCORE})
   }
   return prev;
}, []);

console.log(result);

答案 1 :(得分:0)

下面的代码根据DESCRIPTOR_ID对对象进行分组。首先使用Array.prototype.reduce()方法遍历数组,并获取描述符ID并将其作为键,并计算每个键的总得分。最后使用Object.values()方法获取值。

const sample = [
  {
    DESCRIPTOR: 'HAPPY',
    DESCRIPTOR_ID: 400001,
    QUESTION_ID: 'A_QUES_1',
    CHOICE: 'A',
    SCORE: 1,
    __v: 0,
  },
  {
    DESCRIPTOR: 'HAPPY',
    DESCRIPTOR_ID: 400001,
    QUESTION_ID: 'A_QUES_2',
    CHOICE: 'B',
    SCORE: 2,
    __v: 0,
  },
  {
    DESCRIPTOR: 'SAD',
    DESCRIPTOR_ID: 400002,
    QUESTION_ID: 'B_QUES_1',
    CHOICE: 'A',
    SCORE: 2,
    __v: 0,
  },
  {
    DESCRIPTOR: 'SAD',
    DESCRIPTOR_ID: 400002,
    QUESTION_ID: 'B_QUES_2',
    CHOICE: 'B',
    SCORE: 2,
    __v: 0,
  },
];

const ret = Object.values(
  sample.reduce((prev, c) => {
    const p = prev;
    const key = c.DESCRIPTOR_ID;
    if (!p[key]) p[key] = { DESCRIPTOR: c.DESCRIPTOR, TOTAL_SCORE: c.SCORE };
    else p[key].TOTAL_SCORE += c.SCORE;
    return p;
  }, {})
);
console.log(ret);