4 回答

TA貢獻1719條經(jīng)驗 獲得超6個贊
您可以使用相同的方法過濾地圖并平坦所有數(shù)組。
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條經(jīng)驗 獲得超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條經(jīng)驗 獲得超3個贊
一條線解決方案:
1.轉(zhuǎn)換為字符串 2.拆分為平面數(shù)組 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條經(jīng)驗 獲得超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 ] ]
改變輸入并測試,
使用矩陣邏輯我們可以激活它
添加回答
舉報