简体   繁体   English

过滤数组返回空

[英]Filter an array returns empty

I'm trying to populate an array with all values retrieved (I am in a loop) and then to delete values already present in the yearsJustSelected array:我试图用检索到的所有值填充一个数组(我在循环中),然后删除已经存在于 yearsJustSelected 数组中的值:

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


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

For example:例如:
loop 1 --> yearsJustSelected=[1, 2, 3] - yearsJustSelectedAll=[1, 2, 3] - yearsJustSelectedFiltered = []循环 1 --> yearsJustSelected=[1, 2, 3] - yearsJustSelectedAll=[1, 2, 3] - yearsJustSelectedFiltered = []
loop 2 --> yearsJustSelected=[2, 3, 4, 5] - yearsJustSelectedAll=[1, 2, 3, 4, 5] - yearsJustSelectedFiltered=[4, 5] --> because [2, 3 ] were already present in the yearsJustSelectedAll in the first loop循环 2 --> yearsJustSelected=[2, 3, 4, 5] - yearsJustSelectedAll=[1, 2, 3, 4, 5] - yearsJustSelectedFiltered=[4, 5] --> 因为 [2, 3 ] 已经存在在第一个循环中的 JustSelectedAll 中

This code:这段代码:

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

always return an empty array.总是返回一个空数组。

  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

You could check if the target array does not have the item.您可以检查目标数组是否没有该项目。 Then push the item to the target 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