Ad
Looping Through Array Of Objects Is Only Returning One Object Of Elements Instead Of Two. What Am I Doing Wrong?
Forewarning I am new to coding so be patient with me.
I'm trying to loop through the "diary" array & the function "howMany" is only returning 2 'Home' elements, when there are 4 elements of 'Home' overall in the "diary" array.
What am I doing wrong? Thank you. :)
Ad
Answer
You're using the includes
method which only returns the boolean. If it's matched, even got 4 matches, the number
only will be increased by 1 for each loop.
This is another way to achieve that by using 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) => {
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: Using reduce
& 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);
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad