Reputation: 4333
How to get the difference of array of objects having different keys by comparing the value?
const array1 = [{
name: 'BMW',
type: 'car'
}]
const array2 = [{
year: '2020',
carName: 'BMW',
model: 'SUV',
value: 'car'
},
{
year: '2019',
carName: 'Benz',
model: 'Sedan',
value: 'car'
},
{
year: '2018',
carName: 'Audi',
model: 'Coupe',
value: 'car'
}
]
const result = array1.filter(
({
car: id1
}) =>
!array2.some(({
carName: id2
}) => id2 === id1)
);
console.log('Result ', result)
Below is what I'm expecting. The resultant array should filter out the results that are not there in array1
[
{
year: '2019',
carName: 'Benz',
model: 'Sedan',
value: 'car'
},
{
year: '2018',
carName: 'Audi',
model: 'coupe',
value: 'car'
}
]
Could anyone please help?
Upvotes: 0
Views: 64
Reputation: 1176
You have a typo in you code. Use comparison with name
and carName
instead of carName
and carName
. This code should work:
array2.filter(({carName}) => !array1.some(({name}) => name === carName));
Upvotes: 0
Reputation: 9652
You could filter out array2 by comparing its name
with carName
property. This will give you items of array2
that are not in array1
const array1 = [{
name: 'BMW',
type: 'car'
}]
const array2 = [{
year: '2020',
carName: 'BMW',
model: 'SUV',
value: 'car'
},
{
year: '2019',
carName: 'Benz',
model: 'Sedan',
value: 'car'
},
{
year: '2018',
carName: 'Audi',
model: 'Coupe',
value: 'car'
}
]
var result = array2.filter(function(obj) {
return !array1.some(function(obj2) {
return obj.carName === obj2.name;
});
});
console.log(result);
Upvotes: 1
Reputation: 62
const array1 = [{
name: 'BMW',
type: 'car'
}]
const array2 = [{
year: '2020',
carName: 'BMW',
model: 'SUV',
value: 'car'
},
{
year: '2019',
carName: 'Benz',
model: 'Sedan',
value: 'car'
},
{
year: '2018',
carName: 'Audi',
model: 'Coupe',
value: 'car'
}
]
const result1 = array2.filter(value => array1.some(arr1Val => arr1Val.name !==
value.carName))
console.log('Result ', result1)
Upvotes: 0
Reputation: 22534
You just need to compare the name
with carName
.
const array1 = [{ name: 'BMW', type: 'car' }],
array2 = [{ year: '2020', carName: 'BMW', model: 'SUV', value: 'car' }, { year: '2019', carName: 'Benz', model: 'Sedan', value: 'car' }, { year: '2018', carName: 'Audi', model: 'Coupe', value: 'car'} ],
result = array2.filter(o => !array1.some(({name}) => name === o.carName));
console.log('Result ', result)
Upvotes: 1