JavaScript - get count of object with specific value [duplicate]

You could take the value as key for counting.

var testData = [{ issue_type: "Warning", created_date: "2019-05-13T13:43:16.437Z" }, { issue_type: "Warning", created_date: "2019-05-13T13:45:16.330Z" }, { issue_type: "Alert", created_date: "2019-05-13T13:43:16.437Z" }, { issue_type: "Alert", created_date: "2019-05-13T13:45:16.330Z" }],
    counts = testData.reduce((c, { issue_type: key }) => (c[key] = (c[key] || 0) + 1, c), {});

console.log(counts);

You can simply use filter.

console.log (
  testData.filter (({issue_type}) => issue_type === 'Warning').length
)
<script>var testData = [
  {
    "issue_type": "Warning",
    "created_date": "2019-05-13T13:43:16.437Z",
  },
  {
    "issue_type": "Warning",
    "created_date": "2019-05-13T13:45:16.330Z",
  },
  {
    "issue_type": "Alert",
    "created_date": "2019-05-13T13:43:16.437Z",
  },
  {
    "issue_type": "Alert",
    "created_date": "2019-05-13T13:45:16.330Z",
  }
]</script>

You could do helper functions which can do that for you based on Array.reduce or Array.filter. For example:

const data = [{
  "issue_type": "Warning",
  "created_date": "2019-05-13T13:43:16.437Z",
}, {
  "issue_type": "Warning",
  "created_date": "2019-05-13T13:45:16.330Z",
}, {
  "issue_type": "Alert",
  "created_date": "2019-05-13T13:43:16.437Z",
}, {
  "issue_type": "Alert",
  "created_date": "2019-05-13T13:45:16.330Z",
}]

let countValuesByKey = (arr, key) => arr.reduce((r, c) => {
  r[c[key]] = (r[c[key]] || 0) + 1
  return r
}, {})

let countValue = (arr, key, value) => arr.filter(x => x[key] === value).length

console.log(countValuesByKey(data, 'issue_type'))
console.log(countValue(data, 'issue_type', 'Warning'))
console.log(countValue(data, 'issue_type', 'Alert'))

countValuesByKey would count the different values of the props based on the passed key. countValue would only count specific value by simply filtering the passed array.


use .filter() and get array length from the array returned by filter.

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

var testData = [
  {
    "issue_type": "Warning",
    "created_date": "2019-05-13T13:43:16.437Z",
  },
  {
    "issue_type": "Warning",
    "created_date": "2019-05-13T13:45:16.330Z",
  },
  {
    "issue_type": "Alert",
    "created_date": "2019-05-13T13:43:16.437Z",
  },
  {
    "issue_type": "Alert",
    "created_date": "2019-05-13T13:45:16.330Z",
  }
]

console.log(testData.filter(item => item.issue_type === 'Warning').length)