如何循环遍历包含O(n)时间内数组的对象的数组



这是我的数据示例。我希望能够遍历每个对象,然后遍历内容并将其与某些对象进行比较。我想知道我怎么能在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
}
]

很难在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

如果我把你弄糊涂了,很抱歉,如果你想在两个数组中进行比较,那么你可以在下面尝试。

当然,您必须在两个数组之间有一个公共键,这样您就可以将一个数组转换为对象,并在迭代另一个数组时通过该唯一键读取值。时间复杂度为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.
}
});

最新更新