我有一个小的算法,可以通过另一个数组中的值过滤数组:
const temp = [];
autocompleteItems.forEach(autocompleteItem => {
this.cashDataSource.forEach(cashItem => {
if (cashItem.material === autocompleteItem.title) {
temp.push(cashItem);
}
})
});
this.cashDataSource = temp;
// This can't contains duplicate.
autocompleteItems = [
{
title: '1'
},
{
title: '2'
}
]
cashDataSource = [
{
material: '1'
},
{
material: '1'
}
{
material: '2'
},
{
material: '2'
}
]
使用标准JavaScript方法(例如map
,但不包括两个)的标准javascript方法(例如reduce
等解决方案)。哪个可能实现相同的行为,也许没有温度变量?
答案 0 :(得分:1)
假设您要使用的是cashDataSource
过滤autocompleteItems
,则可以执行以下操作:
const autocompleteItems = [{ title: '1' }, { title: '2' }]
const cashDataSource = [{ material: '1' }, { material: '2' }, { material: '3' }, { material: '4' }]
// get the values in an array e.g. ['1', '2']
const autoValues = autocompleteItems.reduce((r,c) => (r.push(c.title), r), [])
// filter `cashDataSource` against the autoValues
const r = cashDataSource.filter(y => autoValues.includes(y.material))
console.log(r)