Home > Back-end >  Loop through array of arrays and combine arrays depending on elements
Loop through array of arrays and combine arrays depending on elements

Time:01-26

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:

  • the number of array items length is the same for all but can go up.
  • there would always be a 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)

Thanks

CodePudding user response:

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

  •  Tags:  
  • Related