Search code examples
javascriptarraysclasslastindexof

Searching an array for the lastIndexOf where class property is true


I have an array of classes which all have a property of isPurchased, I want to return the last item in the array which has the value set to true.

function ShopItem = new function(id, name, isPurchased) {
    this.id = id;
    this.name = name;
    this.isPurchased = isPurchased;
}    

var apple = ShopItem(1, "Apple", false);
var banana = ShopItem(2, "Banana", true);
var pear = ShopItem(3, "Pear", false);

var shopItems = [apple, banana, pear];

var x = shopItems.lastIndexOf(this.isPurchased == true);
console.log(x);

When I do console.log(x); I want it to return the banana class.

Everything works fine until I try to find the last item and for this I tried to use:

var x = shopItems.lastIndexOf(this.isPurchased == true);

But it returns -1.

Edit:

I have a way to solve the solution by using the code:

var y = null;

for(var o in shopItems) {
    if(shopItems[o].isPurchased == true) {
        y = shopItems[o];
    }
}

console.log(y);

But if lastIndexOf can solve my problem for me then I would rather use that instead of reinventing the wheel.


Solution

  • lastIndexOf searches for values and doesn’t check conditions, plus this.isPurchased == true is an expression, not a lambda. It’d be akin to checking shopItems.lastIndexOf(true). This isn’t built into JavaScript (not even in ES6, which offers Array.prototype.find[Index] but not findLast), so you’ll have to build it yourself:

    function findLast(items, predicate) {
        for (var i = items.length - 1; i >= 0; i--) {
            var item = items[i];
    
            if (predicate(item)) {
                return item;
            }
        }
    }
    

    and use it with a function to call back:

    var x = findLast(shopItems, function (item) {
        return item.isPurchased;
    });