Javascript filter was unfair

61 Views Asked by At

I'm trying to get existCount from an array, which has id in selected array.

But something went wrong, I had an item with id = 5493 but existCount.length 0

My JS code:

var existCount = $scope.selectedScript.filter(function (item) {
    return item.id === script.script_id;
});
console.log('existCount.length ', existCount.length);
console.log('$scope.selectedScript ', $scope.selectedScript);
console.log('script.script_id ', script.script_id);

Chrome Console view:

https://i.stack.imgur.com/4UVWw.png

// Sorry I forgot the first output line, but this line's at the top of $scope.selectedScript and it was existCount.length = 0

Where my fault?

How can I fix it?

Thanks!

2

There are 2 best solutions below

1
On BEST ANSWER

Change return item.id === script.script_id; to return item.id == script.script_id;

In your case: item.id was a number, script.script_id was a string. You can see it in chrome debug by color, black for string, blue for number.

=== is the hard way to compare in JS.

You can see at https://stackoverflow.com/a/359509/8572205

So === return false and no item added into existCount

0
On

if you use triple-equals ===, make sure both the values in comparison are of same type. I suspect script.script_id is a string.

Try changing === to ==