Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

search within an array in javascript

I've been trying for a while now to search within an array, I've looked at all the other questions that even somewhat resemble mine and nothing works, so I'm asking for any help you can give now..

I have an array with a more complex insides than a simple string array

    var elementDefns = [
    {"element":"water", "combos": {"air":"steam", "earth":"sand"} },
    {"element":"fire", "combos": {"earth":"lava", "air":"energy"} },
    {"element":"air", "combos": {"water":"steam", "earth":"dust"} },
    {"element":"earth", "combos": {"water":"swamp", "fire":"lava"} },
];

Two elements are picked (by the users) which are combined to create new elements. I'd like to search through the elements for any combos that can be made. Ideally, I'd want to use Array.prototype.find, although I can't figure out how to use polyfills correctly and i'm unsure if i'm writing it correctly, so it continues to not work

    var elementOne = $("#board img:first-child").attr('id'); 
    var elementTwo = $("#board img:last-child").attr('id');

    function findElement(element) { 
        return elementDefns.element === elementOne;
    }

board is the id div where the element cards go to once clicked. I also tried a loop

    for (var i=0,  tot=elementDefns.length; i < tot; i++) {
            var indexHelp = elementDefns[i].element;
            var find = indexHelp.search(elementOne);
            console.log(find);
        }

I'm trying to post a question that's not too long, but I'm sure there's lots more about my code i need to adjust in order to do this. I guess I'm just asking if there's something obvious you think i could work on. I've looked at most of the answers on this site to similar problems but its all just going horribly wrong so any other support would be greatly appreciated..

like image 760
mcftdhorappusswrtvo Avatar asked Feb 04 '26 20:02

mcftdhorappusswrtvo


1 Answers

I have an array with a more complex insides than a simple string array

Yes, but why? Get rid of the extra layers and this is trivial

var e1 = "water";
var e2 = "air";

var elementDefns = {
    "water": {"combos": {"air":"steam", "earth":"sand"} },
    "fire":  {"combos": {"earth":"lava", "air":"energy"} },
    "air":   {"combos": {"water":"steam", "earth":"dust"} },
    "earth": {"combos": {"water":"swamp", "fire":"lava"} },
};

elementDefns[e1].combos[e2] = > "steam"

like image 138
Devon Sutherland Avatar answered Feb 07 '26 10:02

Devon Sutherland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!