Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count occurrences of two keys in objects in array

Tags:

javascript

I have the following array with objects and used the following code to creating a tally with the key "id":

var arr=[
{ id: 123, 
  title: "name1",
  status: "FAILED"
},
{
 id: 123,
 title: "name1", 
 status: "PASSED"
},
{
 id: 123,
 title: "name1",
 status: "PASSED"
},
{
 id: 123,
 title: "name1",
 status: "PASSED"
},
{
 id: 1234,
 title: "name2",
 status: "FAILED"
},
{
 id: 1234,
 title: "name2",
 status: "PASSED"
}

];


const test =arr.reduce((tally, item) => {
				
			  if (!tally[item.id]) {
				tally[item.id] = 1;
			  } else {
				tally[item.id] = tally[item.id] + 1;
			  }
			  return tally;
			}, {});
      
console.log(test);

Now what I want to do is to modify the tally to take in consideration the key status as well so the result will be somthing like:

[
{id:123, status:"PASSED", tally:3},
{id:123, status:"FAILED", tally:1},
{id:1234, status:"PASSED", tally:1},
{id:1234, status:"FAILED", tally:1}
]

Any idea? Thanks!

like image 400
Ali Avatar asked Nov 01 '25 04:11

Ali


1 Answers

Just make the key item.id + item.status, then it's a simple assignment

const res = Object.values(arr.reduce((a, b) => {
  a[b.id + b.status] = Object.assign(b, {tally: (a[b.id + b.status] || {tally: 0}).tally + 1});
  return a;
}, {}));

console.log(res);
<script>
const arr=[
  { id: 123,
    title: "name1",
    status: "FAILED"
  },
  {
    id: 123,
    title: "name1",
    status: "PASSED"
  },
  {
    id: 123,
    title: "name1",
    status: "PASSED"
  },
  {
    id: 123,
    title: "name1",
    status: "PASSED"
  },
  {
    id: 1234,
    title: "name2",
    status: "FAILED"
  },
  {
    id: 1234,
    title: "name2",
    status: "PASSED"
  }

];
</script>
like image 69
baao Avatar answered Nov 03 '25 19:11

baao