0

Can someone please help me fix this function? It will work if I change the two variables to integers (ie: '987') but if I change them to a character value like 'test' it won't search the array.

I'm new to javascript so excuse me if this is an easy fix. Thank you in advance.

var myArray = [{
  'Vendor': '123',
  'Item': '987',
  'ID': '1'
}, {
  'Vendor': '123',
  'Item': '654',
  'ID': '2'
}];

function findById(source, Vendor, Item) {
  return source.filter(function(obj) {
    return +obj.Vendor === +Vendor, +obj.Item === +Item;
  })[0];
}
var vendin = '123';
var prodin = '654';
var result = findById(myArray, vendin, prodin);
console.log(result.ID);

The variables in question are vendin and prodin.

1
  • I'm confused by the comma in your return statement. Didn't you mean to use return +obj.Vendor === +Vendor && +obj.Item === +Item; ? Commented Jul 22, 2014 at 19:45

2 Answers 2

1

Your return statement is wrong, it is only going to return whatever the last statement results in: +obj.Item === +Item, you need to use a logical operator &&,|| between the statements not a comma

return +obj.Vendor === +Vendor, +obj.Item === +Item;

should be

return (+obj.Vendor === +Vendor) && (+obj.Item === +Item);

Also remove the + if testing strings

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

Comments

0

Try this:

var myArray = [{'Vendor': '123','Item':'987','ID':'1'}, {'Vendor': '123','Item':'654','ID':'2'}, {'Vendor': "test",'Item':"test2",'ID':'3'}];

function findById(source, Vendor, Item) {

    var x = source.filter(function( obj ) {
        return (obj.Vendor == Vendor && obj.Item == Item);
    })[ 0 ];
    return x;
}

var vendin = "test";
var prodin = "test2";
var result = findById( myArray,vendin,prodin)

console.log(
result.ID
);

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.