我如何过滤一个对象数组,它本身有一个数组,通过一个过滤器通过数组,其中过滤器通过数组中的所有项目都在对象数组中找到?
用一个例子来解释可能更容易:
const data = [
{user: 'bob', favoriteThings: ['cats', 'dogs', 'movies']},
{user: 'sally', favoriteThings: ['cats', 'movies', 'trees']},
]
const filterByFavs = ['cats', 'trees']
// result should only include [{user: 'sally', favoriteThings: ['cats', 'movies', 'trees']}]
// if filterByFavs is ['cats'], then both users are returned.
// favoriteThings has to have all the items from filterByFavs in order for the filter to apply.
在上面的剪辑中,我试图过滤data
,以便结果仅包括filterByFavs
中所有项目都在favoriteThings
中找到的对象。
我试图用reduce
和filter
来解决这个问题,似乎不能得到预期的结果。
let out = data.filter((fav) => {
return (
fav.favoriteThings.filter((tag) => {
return !filterByFavs.includes(tag);
})
);
});
let a = data.reduce((acc, fav) => {
let favs = fav.favoriteThings;
let allExists = favs.filter((tag) => !filterByFavs.includes(tag.text));
if (allExists) {
acc.push(fav);
return acc;
}
return acc;
}, []);
我在逻辑中面临的问题是,当filterByFavs
只有一个项目时,我可以过滤得很好,但当它有多个项目时则不行。
检查要查找的.every
项是否包含在要迭代的另一个数组中。
const data = [
{user: 'bob', favoriteThings: ['cats', 'dogs', 'movies']},
{user: 'sally', favoriteThings: ['cats', 'movies', 'trees']},
];
const filterByFavs = ['cats', 'trees'];
const result = data.filter(
obj => filterByFavs.every(str => obj.favoriteThings.includes(str))
);
console.log(result);