Alex
Alex

Reputation: 50

JavaScript Array indexOf() Method not working

I am trying to find an item in an array. I get only -1 for my variable a, so the item was not found in my array, but the item is definitely in array.

var sortiment = [];
var geschmack = [];
var kategorie = [];

function filterOptions(eigenschaft, filter){
    inhalt = filter + " = " + eigenschaft;
    console.log(inhalt);
    console.log(sortiment[0]);
    a = sortiment.indexOf(inhalt);
    console.log(a);

    switch(filter) {
        case "sortiment":
            sortiment.push([inhalt]);
            break;
        case "geschmack":
            geschmack.push([inhalt]);
            break;
        case "kategorie":
            kategorie.push([inhalt]);
            break;
        default:
            console.log("FAIL");
    }
}

In case the item is found, I want not to add it to the array.

Upvotes: 0

Views: 2900

Answers (2)

Page
Page

Reputation: 63

Your getting -1 because when you wrote var sortiment = []; that means it was not found in the array when you ran .IndexOf(something)

Here's a refrence : http://www.w3schools.com/jsref/jsref_indexof_array.asp

function filterOptions(eigenschaft, filter){
    inhalt = filter + " = " + eigenschaft;
    console.log(inhalt);
    console.log(sortiment[0]);
    switch(filter) {
        case "sortiment":
            sortiment.push(inhalt);//remove [ ]
            break;
        case "geschmack":
            geschmack.push(inhalt);
            break;
        case "kategorie":
            kategorie.push(inhalt);
            break;
        default:
            console.log("FAIL");
    }
    a = sortiment.indexOf(inhalt); //look for index after .push
    console.log(a);
}

Upvotes: 0

soapergem
soapergem

Reputation: 9989

You're pushing an (inner) array containing a single element (string) into the (outer) array, but then you're searching for the index of a string from the outer array. That's not going to work. In other words, the problem is most likely this:

geschmack.push([inhalt]);

Why are those square brackets there? You probably want this:

geschmack.push(inhalt);

If you want to visualize this, your arrays will end up looking something like this:

[ ["filter1=eigenschaft1"], ["filter2=eigenschaft2"] ]

But you're not searching for ["filter1=eigenschaft1"]; you're searching for "filter1=eigenschaft1", so of course it won't find it. Alternatively you could change this line:

 a = sortiment.indexOf([inhalt]);

But this whole thing already seems a bit convoluted, to be honest.

Upvotes: 1

Related Questions