Reputation: 2563
I have two array, One of them is like this:
const array1 = [
Object {
"ItemId": 1,
},
Object {
"ItemId": 2,
},
]
other array is :
const array2 = [
Object {
"obj1": Object {
"Id": 4736,
},
"obj2": Object {
"ItemId": 1,
},
}
]
I want to get items in array1, which are not equals in obj2 of array2 .
I tried this but doesnt work
array1.filter(function (item) {
return array2.map((x) => {
return x.obj2 != item;
});
Upvotes: 0
Views: 237
Reputation: 1593
instead of array2.map, you're looking for Array.protype.some or Array.prototype.every. Why?
array1.filter is expecting a truthy value for every item.
array2.map is returning an array (!) with the results of its callback. In your case it's the result of each comparisson x.obj2 != item
. It could look something like this: [true, false]
. But this array will always evaluate to true.
array2.some() or array2.every() also iterate over the array but will return a boolean for the condition you're using. You can try for yourself and check the code sample afterwards.
const array1 = [
{
"ItemId": 1,
},
{
"ItemId": 2,
},
];
const array2 = [
{
"obj1": {
"ItemId": 4736,
},
"obj2": {
"ItemId": 1,
},
},
];
// errornous filter usage
const test = array1.filter(item => {
const arr = array2.map(x => x.obj2 !== item);
return arr;
});
// suggestion
const filteredResult = array1.filter(item => {
// both ways work
// return array2.every(x => x.obj2.ItemId !== item.ItemId);
return !array2.some(x => x.obj2.ItemId === item.ItemId);
});
console.log('initial result', test);
console.log('correct result', filteredResult);
Upvotes: 1
Reputation: 446
Try this
array1=array1.filter((item) => {
return array2[0].obj2.ItemId !== item.ItemId;
})
Upvotes: 0