0

I have written a function that iterates over array and returns object and its value if a match is found.

Somehow, when I call the function with its arguments, it always prints undefined on browser console.

Not sure what I am missing, but in function, when I console.log(v), I get the values, but not when calling the function.

HTML code:

<div class="accounts">
1<input name="1" value="" /><br>
2<input name="2" value="" /><br>
3<input name="3" value="" /><br>
4<input name="4" value="" /><br>
5<input name="5" value="" /><br>
6<input name="6" value="" /><br>
7<input name="7" value="" /><br>
8<input name="8" value="" /><br>
9<input name="9" value="" /><br>
10<input name="10" value="" /><br>
11<input name="11" value="" /><br>
</div>

JQuery code:

var vendor = [];
vendor = [{"vendor_id":"1","vendorname":"Coke","account_no":"34534554"},{"vendor_id":"2","vendorname":"Pepsi","account_no":"34634532"},{"vendor_id":"3","vendorname":"Dr. Pepper \/ 7 Up","account_no":"56754568"},{"vendor_id":"4","vendorname":"Frito Lay","account_no":"676554544"},{"vendor_id":"5","vendorname":"Blue Bunny","account_no":"678476543"},{"vendor_id":"6","vendorname":"Yummy","account_no":"9987654"},{"vendor_id":"7","vendorname":"Ork Farm","account_no":"23456767"},{"vendor_id":"8","vendorname":"Borden","account_no":"89765432"},{"vendor_id":"9","vendorname":"Highland","account_no":"2345678987"},{"vendor_id":"10","vendorname":"Nesquek","account_no":"798654324"}];

var getVendors = [];
$('.accounts input').each(function(){ 
    getVendors.push($(this).attr('name'));
});

function vendorAcctCheck (array, value) {
    array.filter(function(v) {
        if (v.vendor_id == value) {
            // console.log(v);
            return v;
        };
    })
    // return false;
}

var vendorData = vendorAcctCheck(vendor, "2");

console.log(vendorData)

Here is my JSFiddler link.

2
  • Note that you are using the return statement inside the callback for array.filter. Commented Sep 2, 2015 at 1:54
  • 1
    you missed a return for array.filter Commented Sep 2, 2015 at 1:58

1 Answer 1

2

You forget to return.

You are using return only in filter's callback but that'll work only for .filter itself.

If you wanna to get filtered data,you have return the filtered data

Try like this

function vendorAcctCheck (array, value) {
   return array.filter(function(v) {
        if (v.vendor_id == value) {
            // console.log(v);
            return v;
        };
    })
    // return false;
}

JSFIDDLE

Sign up to request clarification or add additional context in comments.

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.