Reputation: 51
Trying to create a function that takes its first argument a string and its second argument a JSON LIST:
[
{
"date": "09/09/18",
"how_many": 11,
"species": "XXXXX"
},
{
"date": "04/11/17",
"how_many": 41,
"species": "TTTTTT"
},
{
"date": "17/03/18",
"how_many": 30,
"species": "DDDDDDDD"
},
{
"date": "17/08/18",
"how_many": 31,
"species": "XXXXX"
},
]
If the string is present in the "species" count of each JSON entry, it would return the amount of occurrences.
Essentially, a function that returns the number of occurrences in the array (or list) of objects whose "species" key matches the first argument of the function?
Upvotes: 0
Views: 35
Reputation: 242
Try this:
function getCount(str, jsonArr) {
var match = jsonArr.filter(obj=> obj.species === str);
return match.length;
}
Upvotes: 0
Reputation: 28475
You can use Array.reduce
From Docs,
The reduce() method executes a reducer function (that you provide) on each member of the array resulting in a single output value.
Your reducer function's returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array and ultimately becomes the final, single resulting value.
EXPLANATION
As you now know, reduce function will reduce the array into a single value which here will be the sum of all matching species. The default value of sum is 0
. On iterating, we check species of object against the passed species value in function. If the value matches, add its how_many value to the sum.
ES6
let list = [{"date":"09/09/18","how_many":11,"species":"XXXXX"},{"date":"04/11/17","how_many":41,"species":"TTTTTT"},{"date":"17/03/18","how_many":30,"species":"DDDDDDDD"},{"date":"17/08/18","how_many":31,"species":"XXXXX"}];
function findOccurences(str, arr) {
return arr.reduce((a,c) => a + (c.species === str ? c.how_many : 0), 0);
}
console.log(findOccurences("XXXXX", list));
ES5
let list = [{"date":"09/09/18","how_many":11,"species":"XXXXX"},{"date":"04/11/17","how_many":41,"species":"TTTTTT"},{"date":"17/03/18","how_many":30,"species":"DDDDDDDD"},{"date":"17/08/18","how_many":31,"species":"XXXXX"}];
function findOccurences(str, arr) {
// Here a - accumulator and c - current value
return arr.reduce(function(a, c){
// If the species of object is same as passed value (str), add it to total sum
if(c.species === str) {
a += c.how_many;
}
return a;
}, 0);
}
console.log(findOccurences("XXXXX", list));
Upvotes: 1