Skip to content
Advertisement

Creating an array from values in a loop

I have a loop that looks like this:

var selectionList = document.querySelectorAll(".product");

selectionList.forEach(selectionItem => {
    var selectionItemTitle = selectionItem.querySelector(".product-title");
}

Inside of my loop I want to ad a condition that says “If this title is not equal to NONE, add this to an array with all the others. See below my note in the code:

selectionList.forEach(selectionItem => {
    var selectionItemTitle = selectionItem.querySelector(".product-title");
    if(selectionItemTitle.textContent != 'None'){
        
        // this is where I am stuck (I don't know what to add inside of my condition)

    }
}

Basically what I want to do is, all the “selectionItemTitle” that passes the conditon needs to be added to an array so I can use that array some place else.

Is this even possible?

Quick note: The reason why I am using a loop, is because I have lots of other code in it (the above is just an example). So I really want to stick to the loop.

Advertisement

Answer

If I understand the question correctly, you can create your array and then add to it with push, see comments:

const theArray = []; // *** Create the array
selectionList.forEach(selectionItem => {
    var selectionItemTitle = selectionItem.querySelector(".product-title");
    if(selectionItemTitle.textContent != 'None'){
        
        theArray.push(selectionItemTitle); // *** Add to it

    }
});

But that’s if you want to keep the forEach. You could use filter instead, still doing the other work in the filter callback:

const theArray = [...selectionList].filter(selectionItem => {
    var selectionItemTitle = selectionItem.querySelector(".product-title");
    // At the end, decide whether this entry is kept or discarded
    // (true for keep, false for discard)
    return selectionItemTitle.textContent != 'None';
});

Note the spread so that we turn the NodeList from querySeletorAll into a true array (so it has filter). You can also just use filter directly on the NodeList:

const theArray = Array.prototype.filter.call(selectionList, selectionItem => {
    var selectionItemTitle = selectionItem.querySelector(".product-title");
    // At the end, decide whether this entry is kept or discarded
    // (true for keep, false for discard)
    return selectionItemTitle.textContent != 'None';
});
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement