Why ===
NOT WORKING whereas !==
is working within function in typescript?
const a = [
{id: 4, name: 'Greg'},
{id: 1, name: 'David'},
{id: 2, name: 'John'},
{id: 3, name: 'Matt'},
];
const b = [
{id: 5, name: 'Mathew', position: '1'},
{id: 6, name: 'Gracia', position: '2'},
{id: 2, name: 'John', position: '2'},
{id: 3, name: 'Matt', position: '2'},
];
const s = a.filter(({ id: idv }) => b.every(({ id: idc }) => idv !== idc));
console.log(s);
const r = a.filter(({ id: idv }) => b.every(({ id: idc }) => idv === idc));
console.log(r);
CodePudding user response:
Solution
For second condition to fulfil your requirement, you need to use Array.some(), like this -
const a = [{id: 4, name: 'Greg'},
{id: 1, name: 'David'},
{id: 2, name: 'John'},
{id: 3, name: 'Matt'}, ];
const b = [ {id: 5, name: 'Mathew', position: '1'},
{id: 6, name: 'Gracia', position: '2'},
{id: 2, name: 'John', position: '2'},
{id: 3, name: 'Matt', position: '2'}, ];
const s = a.filter(({ id: idv }) => b.every(({ id: idc }) => idv !== idc));
console.log(s);
const r = a.filter(({ id: idv }) => b.some(({ id: idc }) => idv === idc));
console.log(r);
CodePudding user response:
step through the logic.
In ===
you are asking to filter array a
for every item that has the same id
property as every item in b
. Thus, in order for this to even be plausible every item in array b
must have the same id
. Since every item in array b
has a different value, this will never work.
In !==
you are asking to filter array a
for every item that has does NOT have an item in array b
with the same id
property. Thus, it finds the two items that do not have a matching id
property pair in array b
.
If this is not the logic you are looking for, update the question with what you are wanting to do as there is no error here.
Here are some docs on the two methods you are using: