Search code examples
javascriptarrayseventsweb-applications

How to export array from inside addEventListener to another JS file?


My web app has a filter page, where if the value of the last filter is set, the addEventListener creates an array using filter(), from my dataset array , filterArr, based on the values chosen in the select elements.

How do I export the resulting array to another JS file?
Using export default arrForQuiz generates the error "unexpected token: export".

Have added the code for the addEventListener and a visual of what I am trying for. Besides that, both JS files involved have type="module" and, as in picture, the original dataset array is already imported from a third file.

I am quite new to this. Was getting all kinds of strange errors when I used one JS file (for two pages), so switched to this approach which so far works well. If it's not a great idea, I'm all ears.

Code:

chooseSection.addEventListener("input", () => {
    let arrForQuiz = filterArr.filter( function(el) {
        return  el.book === chooseBook.value &&
                el.chapter === chooseChapter.value &&
                el.section === chooseSection.value;
        }); 
    // export arrForQuiz to another file
});

Visual: enter image description here


Solution

  • After countless tries of different things, this is what worked. Thanks to Andre for the inspiration. His answer should probably work, I think I just wasn't doing it right.

    Solution:
    Pass the selected values to the other js file with sessionStorage and do the filtering there.

    Code in filter.js:
    -> as the value of the last select element changes, store all the selected values in sessionStorage.

    chooseSection.addEventListener("input", () => {
        sessionStorage.setItem('storedBook', chooseBook.value);
        sessionStorage.setItem('storedChapter', chooseChapter.value);
        sessionStorage.setItem('storedSection', chooseSection.value);
    });
    

    Code in script.js:
    -> get the selected values from sessionStorage and use them to filter the data array.

    let selectedBook = sessionStorage.getItem('storedBook');
    let selectedChapter = sessionStorage.getItem('storedChapter');
    let selectedSection = sessionStorage.getItem('storedSection');
    
    let quizArr = mainArr.filter( function(el) {
        return  el.book === selectedBook &&
                el.chapter === selectedChapter &&
                el.section === selectedSection;
    });
    

    Visual:

    Visual of solution