JS实现数组扁平化
一、递归实现
- map实现
const arr = [[0], 1, 2, [3, [4, 5]],[1,2,5,8],6];
Array.prototype.flat = function(){
const result = this.map((item)=>{
if(Array.isArray(item)){
return item.flat();
}else{
return [item];
}
});
// ...扩展运算符能将数组转换为逗号分割的参数序列
return [].concat(...result)
}
console.log(arr.flat());
let tmp = [...new Set(arr.flat())];
console.log(tmp);
function flatten(arr){
const res = arr.map(item =>{
if(Array.isArray(item)){
return flatten(item);
}else{
return [item];
}
})
return [].concat(...res)
}
console.log(flatten(arr));
- for of 实现
const arr = [[0], 1, 2, [3, [4, 5]],[1,2,5,8],6];
function flatten(sourceArray, flattenedArray = []){
for (const element of sourceArray) {
if (Array.isArray(element)) {
flatten(element, flattenedArray);
} else {
flattenedArray.push(element);
}
}
return flattenedArray;
}
console.log(flatten(arr));
二、flat实现
ES6 中的 flat ⽅法来实现数组扁平化。flat ⽅法的语法:arr.flat ( [depth] )其中 depth 是 flat 的参数,depth 是可以传递数组的展开深度(默认不填、数值是 1),即展开⼀层数组。如果层数不确定,参数可以传进 Infinity,代表不论多少层都要展开:
const arr = [[0], 1, 2, [3, [4, 5]],[1,2,5,8],6];
function flatten(arr){
return arr.flat(Infinity);
}
console.log(flatten(arr));
三、通过扩展运算符实现
这个⽅法的实现,采⽤了扩展运算符和 some 的⽅法,两者共同使⽤,达到数组扁平化的⽬的
const arr = [[0], 1, 2, [3, [4, 5]],[1,2,5,8],6];
function flatten(arr){
while(arr.some(item => Array.isArray(item))){
arr =[].concat(...arr);
}
return arr;
}
console.log(flatten(arr));
JS对象扁平化
//对象扁平化
function flat(obj) {
var newObj = {};
function format(o, pre) {
for (let key in o) {
if (typeof o[key] === 'object') {
if (!pre) {
format(o[key], key);
}else {
if (Array.isArray(o)) {
format(o[key], pre + '[' + key + ']');
}else {
format(o[key], pre + '.' + key);
}
}
}else {
if (!pre) {
newObj[key] = o[key];
}else {
if (Array.isArray(o)) {
newObj[pre + '[' + key + ']'] = o[key];
}else {
newObj[pre + '.' + key] = o[key];
}
}
}
}
}
format(obj, null);
return newObj;
}