Home > Net >  Loop through an array if it finds a key, skip the index for that key, but eventually want to go back
Loop through an array if it finds a key, skip the index for that key, but eventually want to go back

Time:05-19

So this is kind of hard to explain, but basically trying to make a more efficient way of doing the below code...

products.forEach(function(item, index){
    if(item.sale == false ) {
        nonSaleItems  = createEl(item);
    } else {
        saleItems  = createEl(item);
    }
});

items.innerHTML  = nonSaleItems;
items.innerHTML  = saleItems;

products is an array of objects where one of the keys is "sale" and is "false" or "true" for "sale". The idea behind this is to post all the none sale items first, then the sale items goes second - hence the innerHTML of nonSaleItems first, THEN saleItems gets added second.

This code works perfectly, but I feel like there has to be a more efficient / less verbose way to do it instead of two variables of nonSaleItems and saleItems and then two innterHTMLs.

Just curious if anyone had better ideas on how to simplify this or have it better?

CodePudding user response:

You're already doing one loop through all the products, which is a) necessary, and b) about as efficient as it gets.

The best you can do is make your code less verbose. In this case I'm using a ternary to decide which whether to use saleItems or nonSaleItems as the lvalue for = createEl(...):

products.forEach(function(item, index){
    ( item.sale ? saleItems : nonSaleItems )  = createEl(item);
});

items.innerHTML  = nonSaleItems;
items.innerHTML  = saleItems;
  • Related