Array filter linq does not return expected result

69 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:

enter image description here

Chrome Console view:

enter image description here

Where my fault?

How can I fix it?

Thanks!

1

There are 1 best solutions below

0
Ele On

The problem are the types of item.id and script.script_id, you're comparing numbers and strings.

item.id  script_id
  |         |
  v         v
5493 === "5493" -> false

console.log(5493 === "5493");

An alternative is converting to number the script_id

This approach uses the + to convert that string to number and make the correct comparison

console.log(5493 === +"5493");

This is an example to illustrate.

var array = [{id: 4110, name: "Ele"}, {id: 4091, name: "SO"}, {id: 5493, name: "Target"}];

var script_id = "5493";
var result = array.filter(e => e.id === +script_id);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }