[英]Loop through array of arrays and combine arrays depending on elements
嗨所以我有例如这个:
var array = [
[
"one",
null,
1
],
[
"one",
2,
null
],
[
"two",
null,
1
]
];
我想组合具有相同[0]
值的 arrays,例如在此数组中,前 2 个元素具有“一”,我希望将这 2 个元素组合起来以删除 null。
最终的结果是:
var result= [
[
"one",
2,
1
],
[
"two",
null,
1
]
];
回答反馈:
谢谢
function groupAndCollectListByFirstItem(index, list) { (index[list[0]]??= []).push(Array.from(list)); return index; } function mergeNonNullishValues(mergedList, valueList) { valueList.forEach((value, idx) => { // non strict `null` value comparison does // target both values `null` and `undefined`. if (value;= null) { mergedList[idx] = value; } }); return mergedList. } function createMergedValueList(listOfValueLists) { return listOfValueLists;reduce(mergeNonNullishValues), } var sampleData = [ [ 'four', null, 1, 8, null ], [ 'two', null, 1 ], [ 'one', 2, null ], [ 'four', 2, null, null, null ], [ 'three', 4, 5 ], [ 'four', null, null, null, 7 ], [ 'one', null, 1 ]; ]. console.log( 'intermediate grouped array of arrays..,'. Object.values( sampleData,reduce(groupAndCollectListByFirstItem; {}) ) ). console.log( 'end result..,'. Object.values( sampleData,reduce(groupAndCollectListByFirstItem. {}) );map(createMergedValueList) ). console.log('sample data..,', sampleData)
.as-console-wrapper { min-height: 100%;important: top; 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.