[英]Reduce array of arrays and remove null from Javascript data
我很难通过使用 Javascript 去除 null 值和嵌入 arrays 来“压缩”我的语法结果。 我正在使用 Nearley 语法检查器,它可以在匹配句子后运行 JS 函数。 不幸的是,你得到了一系列 arrays 的完整解析结果。 以下是 output 的示例
[
[
[
[
[
[
[ [ 'climb'], [ [ null, 'to' ] ] ],
[ [ null, [ 'alt' ] ] ],
[ 332, [ null, [ 'km' ] ] ]
]
],
[ null ]
]
]
]
]
我想删除所有这些null
值,并可能将所有这些 arrays “压缩”为以下形式:
[
[ 'climb', 'to' ],
[ 'alt', 332, 'km' ]
]
或类似的东西。 我尝试过使用各种filter
方法但没有成功。
您可以使用相同的方法过滤 map 并将所有 arrays 平坦化。
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);
真的吗?...
['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);
一线解决方案:
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);
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 ] ]
改变输入和测试,
使用矩阵逻辑我们可以激活它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.