Search code examples
javascriptarraysfilteringstring-comparison

javascript string comparison issue in array.filter()


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.


Solution

  • 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)