0

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];
        }
      }
    }
7
  • 5
    Where's the Javascript? The posted question does not appear to include any attempt at all to solve the problem. StackOverflow expects you to try to solve your own problem first, as your attempts help us to better understand what you want. Please edit the question to show what you've tried, so as to illustrate a specific roadblock you're running into a minimal reproducible example. For more information, please see How to Ask and take the tour. Commented Dec 11, 2018 at 8:10
  • 1
    On what is the 'total amount' based? What do the numbers in your output array refer to? Commented Dec 11, 2018 at 8:11
  • 1
    please explain your output Commented Dec 11, 2018 at 8:23
  • 1
    @JandreiPitti please edit your question and explain why you want this output. Commented Dec 11, 2018 at 8:28
  • 1
    @JandreiPitti now it's good to answer. Added answer in answer section you can check there. Commented Dec 11, 2018 at 8:29

3 Answers 3

4

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, thank you, i see where i went wrong! sorry about the initial vague post. I was headed in the right direction at least, cheers
1

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)

2 Comments

This way would work however with the caveat that you rely on a fixed, known set of keys
I upvoted, but I marked the other one as the answer because it covers a wider range of use cases and objects, thank you for answering though! I definitely see how this would work as well
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.