繁体   English   中英

如何在 O(n) 时间内循环使用包含数组的对象的数组?

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

看看这些函数,它对你真的很有用: forEachmapreducesortsomeevery

暂无
暂无

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

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