Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to return all events with the same name from dataLayer using JavaScript?

My website has several checkout events corresponding to different stages of the purchase stage (i.e., review order, add personal details, add payment info). Each is called ‘checkout’ in the data layer. I want to return a list of all the events in the dataLayer called ‘checkout’ – so I can compare them.

I can search for individual events by their sequence number

window.dataLayer[245];
window.dataLayer[288];

and I can search by name

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

window.dataLayer.find(x => x.event === "checkout");

however, searching by name only returns the first event called ‘checkout’, I want to return all three, is there a way to do that?

>Solution :

The find() method of Array instances returns the first element in the provided array that satisfies the provided testing function.

To return all events with the name checkout try filter():

The filter() method of Array instances creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.

const checkoutEvents = window.dataLayer.filter(x => x.event === "checkout");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading