Higeath
Higeath

Reputation: 561

Checking on which position is a variable in javascript array

So here is my JavaScript array:

var champions = {   
    "Aatrox":["Blood Well","Dark Flight", "No Q2", "Blood Thirst", "Blood Price", "Blades of Torment", "No E2", "Massacre"],
    "Ahri":["Essence Theft","Orb of Deception", "Fox-Fire", "Charm", "Spirit Rush"],
    "Akali":["Twin Disciplines", "Mark of the Assassin", "Twilight Shroud", "Crescent Slash", "Shadow Dance"],
    "Alistar":["Trample","Pulverize","Headbutt","Triumphant Roar","Unbreakable Will"],
    "Amumu":["Cursed Touch","Bandage Toss","Despair","Tantrum","Curse of the Sad Mummy"]
};

Now I get a variable from a PHP form with champion name so e.g. Akali and also with a spell name so e.g. Twin Disciplines now I want to check if that spell and champion exists in my array and if so on which position it is so:

var championName = echo $champion;
var Spell = echo $championSpells[1][$j];
if($.inArray(championName, champions)==-1){
    var existsInArray = false;
} else{
    var existsInArray = true;
}

And at this point im really confused Spell is = 'Twin Disciplnes' championName is = 'Akali' so with those examples I would want to retrive 1 if it was for example 'Mark of the Assassin' I would want to retrieve 2 because it is 2nd in order.

Upvotes: 1

Views: 97

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386730

In Javascript you can use Array.prototype.indexOf() for the search of an item in an array. The result is the index starting with 0. If not found, the -1 is returned.

var champions = {
    "Aatrox": ["Blood Well", "Dark Flight", "No Q2", "Blood Thirst", "Blood Price", "Blades of Torment", "No E2", "Massacre"],
    "Ahri": ["Essence Theft", "Orb of Deception", "Fox-Fire", "Charm", "Spirit Rush"],
    "Akali": ["Twin Disciplines", "Mark of the Assassin", "Twilight Shroud", "Crescent Slash", "Shadow Dance"],
    "Alistar": ["Trample", "Pulverize", "Headbutt", "Triumphant Roar", "Unbreakable Will"],
    "Amumu": ["Cursed Touch", "Bandage Toss", "Despair", "Tantrum", "Curse of the Sad Mummy"]
};

function getPos(o,n, s) {
    return n in o && o[n].indexOf(s);
}

document.write(getPos(champions, 'Akali', 'Twin Disciplines') + '<br>');
document.write(getPos(champions, 'Akali', 'Mark of the Assassin') + '<br>');

Upvotes: 1

Related Questions