简体   繁体   English

遍历 arrays 数组并根据元素组合 arrays

[英]Loop through array of arrays and combine arrays depending on elements

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.我想组合具有相同[0]值的 arrays,例如在此数组中,前 2 个元素具有“一”,我希望将这 2 个元素组合起来以删除 null。

The final result to be:最终的结果是:

var result= [
   [
      "one",
      2,
      1
   ],
   [
      "two",
      null,
      1
   ]
];

To answer feedback:回答反馈:

  • the number of array items length is the same for all but can go up.数组项长度的数量相同,但 go 最多。
  • there would always be a null vs 'a number'总会有一个 null vs 'a number'
  • the first item of the arrays is always a value (all a timestamp or in this example I used a string) arrays 的第一项始终是一个值(所有时间戳或在此示例中我使用了一个字符串)

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; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM