4 回答
TA贡献1719条经验 获得超6个赞
您可以使用相同的方法过滤地图并平坦所有数组。
const
filter = array => array.flatMap(v => Array.isArray(v)
? filter(v)
: v === null
? []
: v
),
array = [[[[[[[['climb'], [[null, 'to']]], [[null, ['alt']]], [332, [null, ['km']]]]], [null]]]]],
result = filter(array);
console.log(result);
更短的方法
const
filter = array => array
.flat(Infinity)
.filter(v => v !== null),
array = [[[[[[[['climb'], [[null, 'to']]], [[null, ['alt']]], [332, [null, ['km']]]]], [null]]]]],
result = filter(array);
console.log(result);
TA贡献1871条经验 获得超13个赞
真的吗?...那怎么样
['climb', 'to', 'alt', 332, 'km']
?– 彼得·塞利格
那好极了。某种逻辑分组会更好,但嘿,如果没有的话......
...
const sample = [[[[
[[
[ [ 'climb'], [ [ null, 'to' ] ] ],
[ [ null, [ 'alt' ] ] ],
[ 332, [ null, [ 'km' ] ] ]
]],
[ null ]
]]]];
function flatOut(list, item) {
if (Array.isArray(item)) {
item = item.reduce(flatOut, []);
}
return list.concat(item);
}
const result = sample
.reduce(flatOut, [])
.filter(elm => (elm != null)); // non strict equality
//...in order to skip both values, undefined and null.
console.log('result :', result);
TA贡献1875条经验 获得超3个赞
一条线解决方案:
1.转换为字符串 2.拆分为平面数组 3.删除空值
例子:
var arr = [
[
[
[
[
[
[['climb'], [[null, 'to']]],
[[null, ['alt']]],
[332, [null, ['km']]]
]
],
[null]
]
]
]
];
var res = arr.toString().split(",").filter(item => item);
console.log(res);
TA贡献1876条经验 获得超5个赞
let resArr = [];
const findLoc = (arr, loc = []) => {
arr.map((d, i) => {
if (Array.isArray(d)) {
findLoc(d, [ ...loc, i ]);
} else {
if (d !== null) {
// console.log(d, loc);
resArr.push([...loc, d])
}
}
})
}
const a = [
[
[
[
[
[
[ [ 'climb'], [ [ null, 'to' ] ] ],
[ [ null, [ 'alt' ] ] ],
[ 332, [ null, [ 'km' ] ] ],
[ 56, [ null, null, [ [ [8] ] ] ] ]
]
],
[ null ]
]
]
]
];
findLoc(a);
let finalIndex = [...resArr.reverse()[0]];
finalIndex.splice(finalIndex.length -1 , 1);
finalIndex = resArr[0].indexOf(Math.max(...finalIndex));
const finalObj = {};
resArr.forEach((d) => {
finalObj[d[finalIndex]] = finalObj[d[finalIndex]] ? [...finalObj[d[finalIndex]], d[d.length -1]] : [d[d.length -1]]
});
console.log(Object.values(finalObj));
// [ [ "to", "climb" ], [ "alt" ], [ "km", 332 ], [ 8, 56 ] ]
改变输入并测试,
使用矩阵逻辑我们可以激活它
添加回答
举报