Jay
Jay

Reputation: 83

How to count the occurrence of each key within an array of objects?

Say I have an array of objects like so:

[{"taco":"","burrito":"","scone":"","beans":"true"}, 
{"taco":"true","burrito":"","scone":"true","beans":""}, 
{"taco":"true","burrito":"","scone":"","beans":""}, 
{"taco":"true","burrito":"","scone":"","beans":"true"}]

I need to count the occurrence of each element and return in it in an array

[3, 0, 1, 2]

any ideas would be appreciated, thanks!

I have attempted

var a = datasets.reduce(function (item, index) {
    if (typeof item[index] == 'undefined') {
        item[index] = 1;
    } else {
        item[index] += 1;
    }
    return item;
}, {});

could not get anything like that to work so i attempted converting it to json and then removing any key: value pairs with no value then counting remaining ones but have had no success with that either

function tableToJson(table) {
    var data = [];

    var headers = [];
    for (var i=0; i < table[0].rows[0].cells.length; i++) {
        headers[i] = table[0].rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
    }

    for (var i=1; i< table[0].rows.length; i++) {

        var tableRow = table[0].rows[i];
        var rowData = {};

        for (var j=0; j<tableRow.cells.length; j++) {
            rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
        }
        data.push(rowData);
    }
    return data
    }

    function removeEmpty(jsonObj) {
      var newObj = Object.getOwnPropertyNames(jsonObj);
      for (var i = 0; i < newObj.length; i++) {
        var value = newObj[i];
        if (jsonObj[value] === null || jsonObj[value] === undefined) {
          delete jsonObj[value];
        }
      }
    }

Upvotes: 0

Views: 2772

Answers (3)

adiga
adiga

Reputation: 35212

You can loop through the array and then loop through the keys of each object. Then increment the key of the countObject if it already exists or assign it zero.

This is dynamic. Even if one of the object has an extra key, it will count them. This doesn't expect all the items of array to have the same keys.

var array = [
 {"taco":"","burrito":"","scone":"","beans":"true"}, 
 {"taco":"true","burrito":"","scone":"true","beans":""}, 
 {"taco":"true","burrito":"","scone":"","beans":""}, 
 {"taco":"true","burrito":"","scone":"","beans":"true"} 
]

var countObject = {};

array.forEach(item => {
    Object.keys(item).forEach(key => {
        if (item[key] === "true")
            countObject[key] = countObject[key] + 1 || 1
        else
            countObject[key] = countObject[key] || 0
    })
})

console.log(countObject); // get the key and count pair
console.log(Object.values(countObject)); // get the counts in an array

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37755

You can try this

You can do it with reduce().

What i have done is first i check is the object property of current element if it is already in output object. If it's present than i check the value of current element property. if it is true than i increment the property of output object by 1.

If the object property of current element is not available in output than i check for the value of current element property. if it is true i assign output object property with value 1. if false i assign output object property with 0.

let obj = [{"taco":"","burrito":"","scone":"","beans":"true"}, 
{"taco":"true","burrito":"","scone":"true","beans":""}, 
{"taco":"true","burrito":"","scone":"","beans":""}, 
{"taco":"true","burrito":"","scone":"","beans":"true"}]

let op = obj.reduce((output,current)=>{
  for(let key in current){
    if( output[key] ){
      if( current[key] ) output[key]+=1;
    } else {
      if( current[key] ){
        output[key] = 1;
      } else{
        output[key] = 0;
      }
    }
  }
  return output;
},{})

console.log(op);

Upvotes: 4

Jack Bashford
Jack Bashford

Reputation: 44087

Try this:

var data = [{
      taco: "",
      burrito: "",
      scone: "",
      beans: "true"
    },
    {
      taco: "true",
      burrito: "",
      scone: "true",
      beans: ""
    },
    {
      taco: "",
      burrito, "true",
      scone: "",
      beans: "",
      },  {
        taco: "true",
        burrito: "",
        scone: "",
        beans: "true"
      }]

    var total = [0, 0, 0, 0];

    data.forEach(function(obj) {
      if (obj.taco) {
        total[0]++;
      }
      if (burrito) {
        total[1]++;
      }
      if (obj.scone) {
        total[2]++;
      }
      if (obj.beans) {
        total[3]++;
      }
    })

    console.log(total)

Upvotes: 1

Related Questions