我有一个像这样的二维矩阵,其中第一行是列名,其他行是值。
var datatable = [
["a", "b", "c", "d"], //first row are columns names
[ 1, 0, null, 3 ], //other rows are values
[ 6, null, null, 8 ]
];
我想在所有值都为 null
时删除列,如下所示:
var datatable = [
["a", "b", "d"], //first row are columns names
[ 1, 0, 3 ], //other rows are values
[ 6, null, 8 ]
];
行数和列数可以变化。如果有一种紧凑而快速的方法可以使用 lodash 实现它,那就太完美了。
最佳答案
使用 .flow()
创建一个使用 _.unzip()
转置数组的函数,拒绝所有 null
的数组值,然后将数组解压缩回原始形式:
const { flow, partialRight: pr, unzip, reject, tail, every, isNull } = _; // convert to imports
const fn = flow(
unzip,
pr(reject, flow(tail, pr(every, isNull))),
unzip,
);
const datatable = [
["a", "b", "c", "d"], //first row are columns names
[ 1, 0, null, 3 ], //other rows are values
[ 6, null, null, 8 ]
];
const result = fn(datatable);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
还有更简洁的 lodash/fp 解决方案:
const { flow, unzip, reject, tail, every, isNull } = _; // convert to imports
const fn = flow(
unzip,
reject(flow(
tail,
every(isNull)
)),
unzip,
);
const datatable = [
["a", "b", "c", "d"], //first row are columns names
[ 1, 0, null, 3 ], //other rows are values
[ 6, null, null, 8 ]
];
const result = fn(datatable);
console.log(result);
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
关于javascript - lodash - 如果所有值都为空,则从数据表(二维矩阵)中删除列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54598697/