[英]How can I loop through an array with objects that contains an array in O(n) time?
這是我的數據的一個例子。 我希望能夠遍歷每個 object 然后遍歷內容並將其與某些內容進行比較。 我想知道如何在 O(n) 時間內做到這一點?
[
{
timeCreated: 'Mon Apr 05 2021 18:13:19 GMT-0700 (Pacific Daylight Time)',
_id: 606bb5af8f573f1edcb2098c,
conversationID: 'nWdSPC3xoVta9BBISWnXZ3Gk',
sender: 606b9712af2e6611dde79c63,
contents: [ [Object] ],
__v: 0
},
{
timeCreated: 'Mon Apr 05 2021 18:41:10 GMT-0700 (Pacific Daylight Time)',
_id: 606bbc36cc470f20c64ebfc8,
conversationID: 'nWdSPC3xoVta9BBISWnXZ3Gk',
sender: 606b9712af2e6611dde79c63,
contents: [ [Object] ],
__v: 0
}
]
對不起,如果我讓你感到困惑,如果你想在兩個 arrays 中進行比較,那么你可以在下面嘗試。
當然,您必須在兩個 arrays 之間有一個公共鍵,因此您可以將一個數組轉換為 object 並在迭代其他數組時通過該唯一鍵讀取值。 時間復雜度為O(M + N)
const arr1 = [{id: 1, value: 'a'}, {id: 2, value: 'b'}, {id: 3, value: 'c'},{id: 4, value: 'd'}]; const arr2 = [{id: 1, value: 'x'}, {id: 4, value: 'y'}]; //converting arr1 to Object const arr1Hash = arr1.reduce((acc, item) => { acc[item.id] = item; return acc; }, {}); // loop second array based on your need arr2.forEach(ele => { if (arr1Hash[ele.id]) { // perform rest of the work here if you find matching. } });
很難在 0(n) 時間內查看contents
屬性中的每個元素。
但在這個例子中,你會知道如何用不同的方法來做這件事,
let data = [ { timeCreated: 'Mon Apr 05 2021 18:13:19 GMT-0700 (Pacific Daylight Time)', _id: '606bb5af8f573f1edcb2098c', conversationID: 'nWdSPC3xoVta9BBISWnXZ3Gk', sender: '606b9712af2e6611dde79c63', contents: [ { id: 1, title: 'something' }, { id: 2, title: 'something 2' } ], __v: 0 }, { timeCreated: 'Mon Apr 05 2021 18:41:10 GMT-0700 (Pacific Daylight Time)', _id: '606bbc36cc470f20c64ebfc8', conversationID: 'nWdSPC3xoVta9BBISWnXZ3Gk', sender: '606b9712af2e6611dde79c63', contents: [ { id: 3, title: 'something 3' }, { id: 4, title: 'something 4' } ], __v: 0 } ]; // Select a data that contains the id = 1 in the contents property. let selected_data1 = data.find(obj => obj.contents.find(content => content.id === 1)) console.log(selected_data1); // returns the 1st object // Select contents of object that contains IDs (1,3) let selected_data2 = data.reduce((a, b) => a = [...a, b.contents.find(content => [1,3].includes(content.id))], []) console.log(selected_data2); // returns [{ id: 1, title: 'something' }, { id: 3, title: 'something 3' }] // Select all data but filter contents that contains IDs (1,3) let selected_data3 = data.map(obj => ({...obj, contents: obj.contents.filter(content => [1,3].includes(content.id))})) console.log(selected_data3); // returns all objects but filtered the contents property
看看這些函數,它對你真的很有用: forEach
、 map
、 reduce
、 sort
、 some
、 every
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.