Instead of using the includes
method which only returns a boolean, you can achieve the desired result by utilizing the filter
method.
let diary = [];
const addEntry = (events) => {
diary.push({ events });
};
addEntry(['Home', 'Work', 'Park', 'Beach', 'Home']);
addEntry(['Work', 'Home', 'Store', 'Gas Station', 'Home']);
const howMany = (event, journal) => {
let number = 0;
for (let i = 0; i < journal.length; i++) {
let entry = journal[i];
number += entry.events.filter((e) => e === event).length;
}
console.log(`You did that ${number} time(s)`);
};
howMany('Home', diary);
console.log(diary);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Update: Implementing reduce
and filter
.
let diary = [];
const addEntry = (events) => {
diary.push({ events });
};
addEntry(['Home', 'Work', 'Park', 'Beach', 'Home']);
addEntry(['Work', 'Home', 'Store', 'Gas Station', 'Home']);
const howMany = (event, journal) =>
journal.reduce(
(acc, curr) => acc + curr.events.filter((e) => e === event).length,
0
);
const number = howMany('Home', diary);
console.log(`You did that ${number} time(s)`);
console.log(diary);