繁体   English   中英

过滤数组返回空

[英]Filter an array returns empty

我试图用检索到的所有值填充一个数组(我在循环中),然后删除已经存在于 yearsJustSelected 数组中的值:

yearsJustSelected.forEach((el:any)=>{
    yearsJustSelectedAll.push(el);
  });


  yearsJustSelectedFiltered = yearsJustSelected.filter((el: any) => !yearsJustSelectedAll.includes(el));

例如:
循环 1 --> yearsJustSelected=[1, 2, 3] - yearsJustSelectedAll=[1, 2, 3] - yearsJustSelectedFiltered = []
循环 2 --> yearsJustSelected=[2, 3, 4, 5] - yearsJustSelectedAll=[1, 2, 3, 4, 5] - yearsJustSelectedFiltered=[4, 5] --> 因为 [2, 3 ] 已经存在在第一个循环中的 JustSelectedAll 中

这段代码:

yearsJustSelectedFiltered = yearsJustSelected.filter((el: any) => !yearsJustSelectedAll.includes(el));

总是返回一个空数组。

  yearsJustSelected.forEach((el:any)=>{
    yearsJustSelectedAll.push(el);
  });
// The code above will add all elements in yearsJustSelected into yearsJustSelectedAll
// making the two arrays the same.

There are no instances where one array has elements that are not in the other array

您可以检查目标数组是否没有该项目。 然后将项目推送到目标数组。

 function select(source, target) { source.forEach(v => target.includes(v) || target.push(v)); } var yearsJustSelectedAll = []; select([1, 2, 3], yearsJustSelectedAll); console.log(...yearsJustSelectedAll); select([2, 3, 4, 5], yearsJustSelectedAll); console.log(...yearsJustSelectedAll); select([4, 5], yearsJustSelectedAll); console.log(...yearsJustSelectedAll);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM