Hi so I have for example this:
var array = [
[
"one",
null,
1
],
[
"one",
2,
null
],
[
"two",
null,
1
]
];
I would like to combine the arrays that have the same [0]
value, for example in this array the first 2 elements have the "one" and I want those 2 combined to remove the null.
The final result to be:
var result= [
[
"one",
2,
1
],
[
"two",
null,
1
]
];
To answer feedback:
Thanks
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; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.