![](/img/trans.png)
[英]Filter an array of objects based on array property containing all values from another array
[英]How to filter an arrayof objects from all elements of another array of object on values of a common property
假設有一個對象數組,例如:
var arr1 = [{t:new Date('2020-09-12'),NO:2},{t:new Date('2020-09-14'),NO2:20}];
var arr2 = [{t:new Date('2020-09-12'),CO:2}];
我想使用 arr2 的元素過濾 arr1 的元素,以便排除具有相同 t 值的元素。 我看到了類似的答案,但對於簡單的數組,有人建議使用includes
。 我想知道是否可以使用類似的方法。 我試過:
var arr1 = [{ t: new Date('2020-09-12'), NO: 2 }, { t: new Date('2020-09-14'), NO2: 20 }], arr2 = [{ t: new Date('2020-09-12'), CO: 2 }], res = arr1.filter(f => !arr2.includes(ft)); console.log(res);
但它不起作用。 有什么建議嗎? 提前致謝。
你可以在地圖arr2
到的時間序列,並用它來從排除時間arr1
使用includes
const arr1 = [ { t: new Date("2020-09-12"), NO: 2 }, { t: new Date("2020-09-14"), NO2: 20 }, ] const arr2 = [{ t: new Date("2020-09-12"), CO: 2 }] const res = arr1.filter( ({ t }) => !arr2.map(({ t }) => t.getTime()).includes(t.getTime()) ) console.log(res)
您可以簡單地使用過濾器來獲得結果。
var arr1 = [{ t: new Date('2020-09-12'), NO: 2 }, { t: new Date('2020-09-14'), NO2: 20 }], arr2 = [{ t: new Date('2020-09-12'), CO: 2 }], res = arr1.filter(f => arr2.filter(time => time.t.getTime() != ftgetTime()).length); console.log(res);
如果您想使用包含,要建立在您擁有的基礎上,您需要有一個更簡單的數組或使用不同的函數(如 some )來檢查該值是否存在於數組中的任何對象中。
var arr1 = [{t:new Date('2020-09-12'),NO:2},{t:new Date('2020-09-14'),NO2:20}],
var filterDates = [{t:new Date('2020-09-12'),CO:2}].map(v=>v.t),
res = arr1.filter(f => !filterDates.includes(f.t));
或者
var arr1 = [{t:new Date('2020-09-12'),NO:2},{t:new Date('2020-09-14'),NO2:20}],
res = arr1.filter(f => !arr2.some(v=>v.t===f.t));
您可以使用數組的 array.filter 屬性使用 t 鍵過濾掉不相似的對象,例如在此處進行檢查 ::
var arr1 = [{t:new Date('2020-09-12'),NO:2},{t:new Date('2020-09-14'),NO2:20}];
var arr2 = [{t:new Date('2020-09-12'),CO:2}];
const uniqueElementsArray = arr1.filter(element => {
// Checking if an element in arr1 is also in arr2
let isDuplicate = arr2.some(e => e.t.getTime() === element.t.getTime())
return !isDuplicate
})
console.log(uniqueElementsArray)
// Would return the array below
// [ { t: 2020-09-14T00:00:00.000Z, NO2: 20 } ]
所述Array.some方法檢查在ARR2的元素中的至少一個是否具有相同的時間(t)作為ARR1的當前元素Array.filter是目前。 在此處閱讀有關 Array.some 的更多信息
t.getTime()用於將元素的日期 ( t ) 轉換為毫秒以比較日期
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.