0

I wrote this code example to know the index position of an element that has a specific value in "Name". My variable data contains a list of those elements.

var data = {"Attributes":[
    {"Name":"bedrooms","Value":"4"},
    {"Name":"bathrooms","Value":"2"},
    {"Name":"property_type","Value":"House"},
    {"Name":"rateable_value","Value":"$780,000"},
    {"Name":"price","Value":"Price by negotiation"},
    {"Name":"location","Value":"13"},
    {"Name":"district","Value":"Queenstown-Lakes"},
    {"Name":"suburb","Value":"Lower Shotover"},
    {"Name":"region","Value":"Otago"},
    {"Name":"floor_area","Value":"254m²"},
    {"Name":"land_area","Value":"1690m²"},
    {"Name":"property_id","Value":"CBM959"},
    {"Name":"in_the_area","Value":"playground"},
    {"Name":"parking","Value":"Large double garage"}
]}

find_index = function(list, str){
        list.each(function(index, value){
            console.log("Comparing "+value.Name+" with "+str);
            if(value.Name == str){
                return index;
            }
        });
    };

console.log(find_index($(data.Attributes), "bedrooms"))

When I execute this code, it prints in the log all the comparisons and then return "undefined". What I was expecting is to stop iterations when comparison succeeded, and return 0, which is the position of the element with name "bedrooms".

What is happening here? and how can I solve it?

1
  • Your return statement returns from the internal, anonymous function, not the find_index function. Commented Nov 15, 2013 at 18:52

3 Answers 3

3

You need to return the value from your function.

Try

find_index = function(list, str){
    var idx;
        list.each(function(index, value){
            console.log("Comparing "+value.Name+" with "+str);
            if(value.Name === str){
                idx = index;
                return false; //Exit out of the loop after the match
            }
        });
    return idx;
 };

Return value in .each loop is used as a boolean value to exit or continue the loop.

Also you don't need to create a jquery object, you can just use $.each on arrays as is like this:

find_index = function(list, str){
        var idx;
            $.each(list, function(index, value){
                 if(value.Name === str){
                    idx = index;
                    return false; //Exit out of the loop after the match
                }
            });
        return idx;
     };
console.log(find_index(data.Attributes, "bedrooms"));

You can infact simplify this much better to, especially if you want to get multiple matches. But there is no way to break out of map though:

find_index = function(list, str){
  return $.map(list, function(val, idx){
       if(val.Name === str) return idx;
   })[0]; //for multiple matches remove 0
};

console.log(find_index(data.Attributes, "district"));
Sign up to request clarification or add additional context in comments.

Comments

1

Incase, the string comparison is failing try using localeCompare; this comes into rescue to match strings exactly.

find_index = function(list, str){
var localIndex;
    list.each(function(index, value){
        console.log("Comparing "+value.Name+" with "+str + index);
        if(str.localeCompare(value.Name) == 0)
        {

            localIndex = index;
            return false;
        }

    });
    return localIndex;
};

console.log(find_index($(data.Attributes), "bedrooms"));

Comments

0

The each function won't stop (break) unless you return false. You could have a variable you assign the matching index to and then return false.

Comments

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.