[英]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.