我有两个大小为m&的数组。分别为
数组1 :(说出用户列表和
[
{fName: 'John', lname:'Doe', phone:'303-823-3234'},
{fName: 'Jane', lname:'Doe', phone:'702-919-7408'},
//and so on...
]
数组2 :(说出所有用户必须参与的角色列表,但故意将其分开。
[
{role:'All Users', description: 'All users must be part of this role},
{role:'Email', description: 'All users must have access to an email and so are part of this role'}
//and so on...
]
我需要合并这两个数组来构建类似这样的东西
结果数组:
[
{fName: 'John', lname:'Doe', phone:'303-823-3234', role:'All Users', description: 'All users must be part of this role},
{fName: 'John', lname:'Doe', phone:'303-823-3234', {role:'Email', description: 'All users must have access to an email and so are part of this role'}},
{fName: 'Jane', lname:'Doe', phone:'702-919-7408', role:'All Users', description: 'All users must be part of this role},
{fName: 'Jane', lname:'Doe', phone:'702-919-7408', {role:'Email', description: 'All users must have access to an email and so are part of this role'}},
//and so on...
]
这是我的第一种方法(说方法1)遵守功能性编程原则(即没有副作用)。
//x & y are Array 1 and Array 2 respectively
joinArrays: function(x, y){
x.map(function(user){
return y.map(function(role){
return Object.assign({}, role, x); //Based on comments
})
}
}
但我认为通过以下算法可以进一步降低其复杂性
这是另一种方法(说方法2)
Duplicate each item of the the first array (x) by the size of y (y.length). Say the result is z //Somehow create a new array that duplicates the "references" of each ele in x.
Iterate through z. From zero to y.length*1, copy over properties of y[0] to each object.
And then from y.length*1+1 to y.length*2, copy over properties of y[1] to each object. And so on...
方法1具有O(mn)时间复杂度。 (空间复杂度??,那怎么样 Object.assign和JS mapper fns的复杂性?)
Aproach 2的复杂性:O(mn)+ O(mn)= O(mn)?? (空间复杂度更高?)
对复杂性和任何其他解决方案(仅限功能)的评论更好吗?