Consider the following data:
const filters = ["c", "1"];
const data = [
{
name: 'a',
values: ["a", "b", "c"],
},
{
name: "b",
values: ["a", "z", "1"],
},
{
name: "c",
values: ["z", "y", "x"],
}
];
In order to get all the objects in the data array where the values contain one of the filters, the following can be used:
data.filter(entry => entry.values.some(v => filters.includes(v)));
According to the rules of javascript I'm aware of, you can forego the anonymous/lambda function in the .some() call, in the following way:
data.filter(entry => entry.values.some(filters.includes));
However, this doesn't work, as we get the error TypeError: Cannot convert undefined or null to object. However, doing the following makes it work also, but is redundant and I don't understand why it's necessary:
const inc = (v) => filters.includes(v);
data.filter(entry => entry.values.some(inc));
Is this a bug in the V8 engine (I've tried this in a chrome console and in nodejs) or is it a technical limitation I'm not aware of? If so, can someone explain it to me?
filters.includes.bind(filters)to keep theincludesmethod bound to the appropriate object. And, there's a syntax shortcut under development for this in a future version of Javascript which is think uses::.data.filter(entry => entry.values.some(Array.prototype.includes)). JavaScript function binding (this keyword) is lost after assignment. Even if you passfiltersasthisArgit won't work becauseincludeshas a second parameter: Why does Array.prototype.includes.bind behave unexpectedly?Setinstead of anArrayforvalues. Unless you need the ability to adjust the order or contain duplicates, theSetwould give you the same container aspect, but give you the more efficient.has()operation.