4

I try to dynamically generate a listview in jQuery. This works perfectly for the whole list, but now I need to filter/search/reduce my initial data:

var rezepte = [
{ "name" : "Eierkopf" , "zutaten" : ["Eier", "Zucker"] , "zubereitung" : "alles schön mischen." },
{ "name" : "Käseschnitte" , "zutaten" : ["Käse", "Brot", "Paprika"] , "zubereitung" : "Käse drauf und in den Ofen" },
{ "nme" : "Gemüse-Auflauf" , "zutaten" : ["Lauch"] , "zubereitung" : "1. schneiden 2. Kochen 3. essen" }
];

I would like to filter/search "recipe" by a searcharray like var searcharray = ["Zucker", "Paprika"] resulting in:

var result = [
{ "name" : "Eierkopf" , "zutaten" : ["Eier", "Zucker"] , "zubereitung" : "alles schön mischen." },
{ "name" : "Käseschnitte" , "Zutaten" : ["Käse", "Brot", "Paprika"] , "zubereitung" : "Käse drauf und in den Ofen" }];

I have tried a lot of things within the for loop: filter, map, push - but all without sucess always resuling in undefined objects.

I am also not sure what syntax my recipe Array should be: there must be the possibility of variable amount of "ingredients".

Any help and hint would be most appreciated.

Thanks a lot, Andi

5
  • 1
    Can you please show code which gives you undefined objects? Commented Nov 16, 2012 at 10:04
  • To clarify your question: You want those array entries where at least one entry of the array search is in the embedded array ingredients of the object? Commented Nov 16, 2012 at 10:10
  • @ Philipp: yes, exactly: where at least one entry of the array search is in ingredients. Commented Nov 16, 2012 at 10:15
  • @ FAngel: this is part of what I was trying: var result = []; //var temp = []; //$.each(searcharray, function(index, value) { or for (var i=0; i<searcharray.length; i++) { result = rezepte.filter(function (rez) { return rez.zutaten == searcharray[i] }); } //}); //for (var i=0;i<searcharray.length;i++) { //temp = rezepte.filter(function (rez) { return rez.zutaten //searcharray[i].properties }); //result.push(temp); //} return result; Commented Nov 16, 2012 at 10:19
  • @FAngel currently no issue with undefined objects - I am not even there yet :-) See updated question. Thank you. Commented Nov 16, 2012 at 15:39

2 Answers 2

3

Using native Array functions, this should work:

result = recipes.filter(function(recipe) {
    return search.any(function(ingredient) {
        return recipe.ingredients.indexOf(ingredient) != -1;
    });
});

Using jQuery, it would be

result = $.grep(recipes, function(recipe) {
    for (var i=0; i<search.length; i++)
        if ($.inArray(recipe.ingredients, search[i]) != -1)
            return true;
    return false;
});
Sign up to request clarification or add additional context in comments.

3 Comments

You don't get the alert because the function returns right before it. Notice that typeof [] is "object" because all javascript Arrays are objects, only for primitive values (strings, numbers, undefined...) you get other values. You can test whether an object is an array with isArray (cross-browser jQuery).
appreciate your assistance. Have updated the question and deleted the comments. The ones to FAngel was referring to what I tried earlier (obsolete). There is no issue with undefined objetcs anymore. Current problem is that I would like to implement the $.grep() you showed me. Thx, Andi
It seems good to me, but place the alert either before the for-loop or after the $.grep. If you don't get the correct search results, you also might adapt your searcharray creating, currently the words might contain whitespaces etc.
1
var rezepte = [
{ "name" : "Eierkopf" , "zutaten" : ["Eier", "Zucker"] , "zubereitung" : "alles schön mischen." },
{ "name" : "Käseschnitte" , "zutaten" : ["Käse", "Brot", "Paprika"] , "zubereitung" : "Käse drauf und in den Ofen" },
{ "nme" : "Gemüse-Auflauf" , "zutaten" : ["Lauch"] , "zubereitung" : "1. schneiden 2. Kochen 3. essen" }
];

function search() {
    var search = $("#searchfield").val(); // returns string
    var searcharray = search.split(',');
    if (searcharray == "") {
        check = $.isArray(searcharray);
        alert(check); // true
        return rezepte;
    } else { 
        var result = [];
        alert("till here fine");
        result = $.grep(rezepte, function(rezept) {
            for (var i=0; i<searcharray.length; i++) {
                if ($.inArray(searcharray[i], rezept.zutaten) != -1)
                    return true;
            } 
             return false;
        });
    }
    console.log(result);
    return result;  
}
$(function(){
     $("#search").click(search);
})

I have it working with this code. See demo: http://jsfiddle.net/VcZtE/1/ (results could be seen in browser console). The only difference from your code is here: if ($.inArray(searcharray[i], rezept.zutaten) != -1). According to docs for inArray needle should be a first parameter and array to search in - second. And you have it in opposite way: array is passed as a first param and needle (value to search for) as a second.

1 Comment

Great! Works perfectly in my jQuery project. Issue solved and learnd a lot from all of you guys. Thank you very much. Cheers, Andi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.