【问题标题】:How to count different values of an object inside an array如何计算数组中对象的不同值
【发布时间】:2018-02-07 01:23:06
【问题描述】:

在数据库中,我有两个列:idvalue。我想检查我的result 中有多少不同的id,我该怎么做?

我试图想出一个解决方案,但我没有比countDifferentId(){// do some magic calculations}更成功

result 看起来像这样:

[ RowDataPacket {
    id: 76561198115203520,
    value: 73 },
  RowDataPacket {
    id: 76561198115029751,
    value: 73 }
  RowDataPacket {
    id: 76561198115702984,
    value: 73 },
  RowDataPacket {
    id: 76561198115203520,
    value: 73 } ]

所以countDifferentId()的结果应该是3

【问题讨论】:

    标签: mysql node.js


    【解决方案1】:

    如果你想在 javascript 方面做这项工作,你可以去:

    const rowDataPackets = [
        {
            id: 76561198115203520,
            value: 73
        },
        {
            id: 76561198115029751,
            value: 73
        },
        {
            id: 76561198115702984,
            value: 73
        },
        {
            id: 76561198115203520,
            value: 73
        }
    ];
    
    
    function countDifferentId(array){
        // Object with key=id to count unique ids and value is true (or whatever)
        const uniqueIds = array.reduce((acc, data) => Object.assign(acc, {[data.id]:true}) , {});
        // Number of unique ids is the number of keys
        return Object.keys(uniqueIds).length;
    }
    
    console.log(countDifferentId(rowDataPackets));
    

    【讨论】:

    • 这成功了!非常紧凑和快速,正是我所需要的
    • 注意:我把const uniqueIds = rowDataPackets.reduce改成了const uniqueIds = array.reduce
    • 好收获!很高兴它有帮助:)
    【解决方案2】:

    您不想按查询分组吗?这里有很多例子。例如

    https://www.w3resource.com/mysql/aggregate-functions-and-grouping/aggregate-functions-and-grouping-count-with-group-by.php

    MySQL Query with count and group by

    等等

    如果您只有来自 API 的服务器请求,您可能需要 .创建一个哈希表,如 { 编号:计数 }

    【讨论】:

    • 我希望有一个 JS 解决方案,因为我认为它对我来说更快
    • JS 不一定更快,它通常更好地在服务器之间共享工作。 Group by 是一个不错的选择。如果要获取的行数很多,而您只想数数,最好使用select count(distinct id) from...
    • @RaphaMex 行数不会超过 100,我需要每 1 秒打一次电话,是不是更好?
    • 我做了一个纯JS的解决方案,如果你想试一试比较一下。每秒 100 行,这对任何一种解决方案都不是问题。我只是在评论以防万一您有数千行,最好减轻您的网络。
    • 我同意在查询级别执行此操作是理想的,但有时取决于项目动态,这不是一个可行的选择。
    【解决方案3】:

    函数从一个数组列中获取所有值并作为数组返回。

    然后for循环使用数组来存储计数值,每次检查数组以确保值只计数一次。

    function getCol(myarray, col){ 
        var column = []; 
        for(var i=0; i<myarray.length; i++){ 
            column.push(myarray[i][col]); 
        } 
        return column; 
        }
    
        cols = getCol(result, 'id');
        var count = 0;
        var used = [];
        for(var i = 0; i<cols.length;i++){
             if(!used.indexOf(cols[i])){
                   used.push(cols[i]);
                   count++;
             }
         }
    

    【讨论】:

    • 你能解释一下你的答案吗?
    • 糟糕的堆栈应用发布了两次哦
    • 确实是垃圾
    • 如果我想调用 getCol() 我将如何将 MySQL result 解析到函数中?
    • getCol(result,'id');
    猜你喜欢
    • 2017-09-26
    • 2013-07-29
    • 2020-10-07
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    • 2016-03-20
    相关资源
    最近更新 更多