Search code examples
javascriptarraysstringalgorithmlocal-storage

JavaScript String Splicing does not seem to work


I'm trying to save Expanded/Collapsed states of my Bootstrap Collapses.

I'm saving it in the LocalStorage and reading it out of it.

$(".content-accordion-content").each(function (index) {
                console.log(index, $(this).attr("id"));
                $(this).on("show.bs.collapse", function () {
                    var expandedCollapses = localStorage.getItem("ExpandedCollapses");
                    if (expandedCollapses !== undefined && expandedCollapses !== null && expandedCollapses !== "") {
                        expandedCollapses = expandedCollapses + "|" + $(this).attr("id");
                    }
                    else {
                        expandedCollapses = $(this).attr("id");
                    }
                    localStorage.setItem("ExpandedCollapses", expandedCollapses);
                })
                $(this).on("hide.bs.collapse", function () {
                    var expandedCollapses = localStorage.getItem("ExpandedCollapses");
                    if (expandedCollapses !== undefined && expandedCollapses !== null) {
                        if (!expandedCollapses.includes("|") && expandedCollapses.includes($(this).attr("id")))
                            expandedCollapses = "";
                        else {
                            var ecArr = expandedCollapses.split("|");
                            expandedCollapses = ecArr.splice(ecArr.indexOf($(this).attr("id")), 1).join("|");
                        }
                        localStorage.setItem("ExpandedCollapses", expandedCollapses);
                        console.log(expandedCollapses,$(this).attr("id"));
                    }
                })
            });

It seems to work, but sometimes it removes multiple Entries from the Array.

For example, I open Authors then Open Books then Open Videos. the string Looks like this "Authors|Books|Videos". If I close Books now, it's only "Authors". Can someone help me unstuck my brain?


Solution

  • Whoops, found it. I joined the outcome of the .splice() method. which turns out the be wrong. this here fixed my code

    var ecArr = expandedCollapses.split("|");
    ecArr.splice(ecArr.indexOf($(this).attr("id")), 1);
    expandedCollapses = ecArr.join("|");