This is the 14th day of my participation in the August More Text Challenge
preface
💪~ If you like it, you can like it or leave a comment 💕~~~, thank you ⭐️ 💕 ️~~
1. Use [].concate.apply to achieve dimensionality reduction
var arr=[[1.2], [3.4]].function Jw(obj){
console.log(Array.prototype.concat.apply([],obj))
return Array.prototype.concat.apply([],obj);
}
Jw(arr);
Copy the code
2. If the concat method takes an element, that element is inserted directly into the new array. If the argument is an array, the elements of that array are inserted into the new array
function reduceDimension(arr){
let ret = [];
for(let i=0; i<arr.length; i++){ ret=ret.concat(arr[i]) }console.log(ret)
return ret;
}
reduceDimension(arr)
Copy the code
3. The recursion
function reduceDimension(arr){
let ret = [];
let toArr = function(arr){
arr.forEach(function(item){
item instanceof Array ? toArr(item) : ret.push(item);
});
}
toArr(arr);
console.log(ret)
return ret;
}
reduceDimension([1.2[3.4[5.6]]])
Copy the code
4.flat
let list = [1.2.3[4[5]]];
let res = list.flat(Infinity)
console.log(res) // [1, 2, 3, 4, 5]
Copy the code
5. Reduce transforms a two-dimensional array into a one-dimensional array
let arr = [[0.1], [2.3], [4.5]]
let newArr = arr.reduce((pre,cur) = >{
return pre.concat(cur)
},[])
console.log(newArr); // [0, 1, 2, 3, 4, 5]
Copy the code
6. Reduce transforms multidimensional arrays into one-dimensional arrays
let arr = [[0.1], [2.3], [4[5.6.7]]]
const newArr = function(arr){
return arr.reduce((pre,cur) = >pre.concat(Array.isArray(cur)? newArr(cur):cur),[]) }console.log(newArr(arr)); //[0, 1, 2, 3, 4, 5, 6, 7]
Copy the code
😊 thank you for reading ⭐️⭐ ⭐️. If you like it, you can like it or leave a comment
Past hot articles
- Vue interview summary
- Js Interview questions often contain detailed answers
- Es6 summary
- The JS array reduce() method
- Js array sort ()
- HTML Interview Summary
- CSS Interview Summary
- Summary of wechat mini program interview
- Css3 implementation of animation effects commonly used method guide
- How to use pure CSS to achieve div box four corners ornament