Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 按另一个数组的值筛选一个数组而不使用嵌套的foreach_Javascript_Arrays_Algorithm - Fatal编程技术网

Javascript 按另一个数组的值筛选一个数组而不使用嵌套的foreach

Javascript 按另一个数组的值筛选一个数组而不使用嵌套的foreach,javascript,arrays,algorithm,Javascript,Arrays,Algorithm,我有一个小算法,可以根据另一个数组中的值过滤数组: const temp = []; autocompleteItems.forEach(autocompleteItem => { this.cashDataSource.forEach(cashItem => { if (cashItem.material === autocompleteItem.title) { temp.push(cashItem); } }) }); this.cashDa

我有一个小算法,可以根据另一个数组中的值过滤数组:

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、reduce、filter等,包括foreach,但不包括两种。如果没有临时变量,哪一种可能实现相同的行为?

假设您所追求的是通过自动完成项过滤现金数据源,您可以执行以下操作:

常量自动完成项=[{title:'1'},{title:'2'}] const cashDataSource=[{material:'1'},{material:'2'},{material:'3'},{material:'4'}] //获取数组中的值,例如。['1','2'] const autoValues=autocompleteItems.reducer,c=>r.pushc.title,r,[] //根据自动值筛选'cashDataSource' const r=cashDataSource.filtery=>autoValues.includesy.material
console.logr使用reduce自己测试它。然后,当您在文章中遇到问题时,尝试使用一些示例数据,我觉得更多的上下文可能会有所帮助-autocompleteItem中有什么内容?源数据是什么样子的,预期的输出应该是什么样子的?如果没有这些信息,我觉得我无法为您提供有意义/有帮助的答案…更新问题。为什么这种侵略性打击了我的声誉这是一个小错误,不是垃圾邮件。发生什么事?