const newArr = [] arr2.forEach(item => { this.allOriC.forEach(item2 => { if (item.dataIndex === item2.dataIndex) { newArr.push(item2) } }) })优化下这个代码,返回的新数组item顺序要一致
可以使用JavaScript的Array.prototype.map()和Array.prototype.find()方法来优化这段代码,这样可以保持原数组(arr2)的顺序不变:
- const newArr = arr2.map(item => {
- return this.allOriC.find(item2 => item.dataIndex === item2.dataIndex) || null;
- }).filter(Boolean);
这里做了以下优化:
map()函数遍历arr2,对于arr2中的每个item,在allOriC中查找匹配的元素。find()函数根据条件item.dataIndex === item2.dataIndex查找匹配项。find()返回undefined),则用null填充当前位