javascript string comparison issue in array.filter()

Viewed 2713

I have an array which contains following objects.

myArray = [
    { item: { id: 111557 } },
    { item2: { id: 500600 } }]

and I have a variable

targetItemID = '111557'

Note that one is string, and the ones in array are numbers. I'm trying to get the object having the correct item id.

Here is what I have tried,

    myArray = [
        { item: { id: 111557 } },
        { item2: { id: 500600 } }]


    
    targetItemID = '111557'
    
var newArray = myArray.filter(x => {

    console.log(x.item.id.toString())
    console.log(targetItemID.toString())

    x.item.id.toString() === itemID.toString()

    })

    console.log(newArray);

I expect all matching objects to be added to 'newArray'. I tried to check the values before comparison, They are both strings, they seem exactly same, but my newArray is still empty.

3 Answers
  • Your second object doesn't have an item property and should.
  • You need a return in your filter function.
  • You must compare x.item.id against targetItemID, not itemID. Since you are using console.log() you would have seen and error of itemID id not defined ;).

myArray = [
        { item: { id: 111557 } },
        { item: { id: 500600 } }
];


targetItemID = '111557'
    
var newArray = myArray.filter(x => {

    //console.log(x.item.id.toString())
    //console.log(targetItemID.toString())

    return x.item.id.toString() === targetItemID.toString();
});

console.log(newArray);

you need to return for filter to work:

return x.item.id.toString() === itemID.toString();

There are a few issues here. First, not all your objects have an item property, so you'll need to check it exists. Second, you're comparing them against a non-existent itemID instead of targetItemID, and finally, and @bryan60 mentioned, if you open a block in an anonymous lambda, you need an explicit return statement, although, to be honest, you really don't need the block in this case:

var newArray =
    myArray.filter(x => x.item && x.item.id && x.item.id.toString() === targetItemID)
Related