Suppose, we have two arrays of literals and objects respectively −
const source = [1, 2, 3 , 4 , 5];
const cities = [{ city: 4 }, { city: 6 }, { city: 8 }];We are required to write a JavaScript function that takes in these two arrays. Our function should create a new array that contains all those elements from the array of objects whose value for "city" key is present in the array of literals.
Example
Let us write the code −
const source = [1, 2, 3 , 4 , 5];
const cities = [{ city: 4 }, { city: 6 }, { city: 8 }];
const filterByLiterals = (objArr, literalArr) => {
const common = objArr.filter(el => {
return literalArr.includes(el['city']);
});
return common;
};
console.log(filterByLiterals(cities, source));Output
And the output in the console will be −
[ { city: 4 } ]