【问题标题】:Get count of array objects belonging to a partical ID in JavaScript/Node js获取属于 JavaScript/Node js 中特定 ID 的数组对象的计数
【发布时间】:2019-10-15 23:04:27
【问题描述】:

我有一个这样的数组:

var array = [ 
    [ '2','Yes'],
    [ '2','Yes'],
    [ '2','Yes'],
    [ '3','Yes'],
    [ '3','Yes'],
    [ '4','Yes'],
]

上述数组(2,3 和 4)中的 ID 动态来自服务器响应。 我需要计算特定 ID 的条目数。 我无法弄清楚如何遍历这个数组以获得预期的输出。 预期的输出是:

[{"ID" : "4", Count : "1"},{"ID" : "3", Count : "2"},{"ID" : "2",Count : "3"}]

注意输出是按Count的升序排列的。

这是我尝试过的:

var temp1 = [];
                var temp2 = [];
                var temp3 = [];
                for(var i = 0; i < array.length; ++i){
                     if(array[i][0] == 2){
                        temp1.push(array[i])
                     }
                     if(array[i][0] == 1){
                        temp2.push(array[i])
                     }
                     if(array[i][0] == 3){
                        temp3.push(array[i])
                     }

                }

 var output = [{
                    ID: "2",
                    Count: temp1.length,
                },
                {
                    ID: "1",
                    Count: temp2.length,
                },
                {
                    ID: "3",
                    Count: temp3.length
                }]

console.log(output)

如果数据是动态的,我相信我的做法并不是最好的方法。 我该如何以更好的方式做到这一点?

【问题讨论】:

  • 我正在更新问题,请检查

标签: javascript arrays node.js sorting


【解决方案1】:

Array.prototype.reduce()Object.entries()Array.prototype.sort()Array.prototype.map() 的组合使用会产生这样的结果:

const array = [ 
    [ '2','Yes'],
    [ '2','Yes'],
    [ '2','Yes'],
    [ '3','Yes'],
    [ '3','Yes'],
    [ '4','Yes'],
];

const result = Object.entries(array.reduce((a, [id]) => {
  a[id] = (a[id] || 0) + 1;
  return a;
}, {})).map(([ID, Count]) => ({ID, Count}))
       .sort((a, b) => a.Count - b.Count);

console.log(result);

【讨论】:

【解决方案2】:

您可以使用 map 和 filter 来转换数组并计算出现次数,然后按 count 属性对数组进行排序:

const array = [ 
    [ '2','Yes'],
    [ '2','Yes'],
    [ '2','Yes'],
    [ '3','Yes'],
    [ '3','Yes'],
    [ '4','Yes'],
];

const result = [];
array.forEach( item => {
  if (result.find( id => item[0] === id["ID"])){
    return;
  }
  result.push({"ID": item[0], Count: array.filter(ids =>  ids[0] === item[0]).length});
})

// And then sort it
result.sort( (a,b) => a.Count - b.Count);

console.log(result);

【讨论】:

    【解决方案3】:

    你可以试试这个。

    var array = [ 
        [ '2','Yes'],
        [ '2','Yes'],
        [ '2','Yes'],
        [ '3','Yes'],
        [ '3','Yes'],
        [ '4','Yes'],
    ];
    
    var y = {};
    var z = [];
    array.forEach(x=>{      //creating object which will store freq of Id
      if(!y[x[0]]){
        y[x[0]] = 0;
      }
      y[x[0]]++;
    });
    Object.keys(y).forEach(x=>{   //converting above object to array
      z.push({'ID': x, 'Count':y[x]});
    });
    console.log(z.sort((a,b) => a.Count - b.Count))//sorting array as per requirement

    【讨论】:

      【解决方案4】:

      尝试使用Array#prototype#reduce

      const array = [ 
          [ '2','Yes'],
          [ '2','Yes'],
          [ '2','Yes'],
          [ '3','Yes'],
          [ '3','Yes'],
          [ '4','Yes'],
      ];
      
      const res = array.reduce((acc, curr) => {
      	let foundElement = acc.find(x => x.id === curr[0]);
      	
      	if (!foundElement) {
      		foundElement = {
      			id: curr[0],
      			count: 1
      		};
      		
      		acc.push(foundElement);
      	}
      	else {
      		foundElement.count += 1;	
      	}
      	
      	return acc;
      }, [])
      .sort((a, b) => a.count - b.count);
      
      console.log(res);

      【讨论】:

        【解决方案5】:

        您也可以使用以下代码获得预期的结果。

        var array = [ 
            [ '2','Yes'],
            [ '2','Yes'],
            [ '2','Yes'],
            [ '3','Yes'],
            [ '3','Yes'],
            [ '4','Yes'],
        ]
        
        var arrMap = {}
        
        array.map(item => {
            if(arrMap[item[0]]){
             arrMap[item[0]]++ 
            }else{
             arrMap[item[0]] = 1
            } 
        })
        
        var resultArr = []
        
        for(var keys of Object.keys(arrMap)){
         resultArr.push({"ID":keys,"Count":arrMap[keys]})
        }
        

        【讨论】:

          【解决方案6】:

          如果你想坚持你的 for 循环,一个简单的方法是检查每个项目是否已经包含在输出中,如果是,则增加计数,如下所示:

          var array = [
          [ '2','Yes'],
          [ '2','Yes'],
          [ '2','Yes'],
          [ '3','Yes'],
          [ '3','Yes'],
          [ '4','Yes'],
          ];
          
          var output = [];
          
          for(var i = 0; i < array.length; ++i) {
            if(!output.find(item => item.ID === array[i][0])){
              output.push({'ID': array[i][0], 'Count': 1});
            } else {
              output.find(item => item.ID === array[i][0]).Count += 1;
            }
          }
          output.sort( (a,b) => a.Count - b.Count)
          
          console.log(output);
          

          【讨论】:

          • 我还以为输出刚开始是颠倒过来的,其实按照问题是按Count排序的。
          • @RobbyCornelissen 完全正确 我错过了这个,谢谢 ;)
          猜你喜欢
          • 2017-06-24
          • 2023-02-26
          • 2015-11-19
          • 1970-01-01
          • 1970-01-01
          • 2021-12-18
          • 1970-01-01
          • 2018-07-20
          • 2014-12-04
          相关资源
          最近更新 更多