简体   繁体   English

我如何减少此代码的时间复杂度

[英]How do i reduce time complexity of this code

 let arr = [[{x: 1},{y: 2}],[{z: 3}]] let objs = [] arr.forEach(innerArray => { innerArray.forEach(obj => { objs.push(obj) }) }) console.log(objs) // [{x:1}, {y:2},{z:3}] 

I don't want to map array two time, could you please help me to find the better way of doing this. 我不想两次映射数组,请您帮我找到更好的方法。

You can use Array.prototype.flat() 您可以使用Array.prototype.flat()

Note: All the methods below are just alternative which will have high speed. 注意:以下所有方法都是替代方法,将具有较高的速度。 Your solution has O(n) time-complexity and all the method below have same time-complexity. 您的解决方案具有O(n)时间复杂度,并且以下所有方法都具有相同的时间复杂度。 The time-complexity of merging two arrays is O(n) not O(1) 合并两个数组的时间复杂度是O(n)而不是O(1)

 let arr = [[{x: 1},{y: 2}],[{z: 3}]] let objs = arr.flat(); console.log(objs) 

Or another way is using concat() and reduce() 或者另一种方法是使用concat()reduce()

 let arr = [[{x: 1},{y: 2}],[{z: 3}]] let objs = arr.reduce((ac,a) => ac.concat(a),[]) console.log(objs) 

A better idea suggested in comments is using apply() 评论中建议的一个更好的主意是使用apply()

 let arr = [[{x: 1},{y: 2}],[{z: 3}]] let objs = [].concat.apply([], arr) console.log(objs) 

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

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