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
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");