Search code examples
javascriptarrayslodash

LoDash: How to remove null values and index of null values from two arrays with _.flow?


Problem

I have an array of arrays:

const multiple = [[1, 2, null, 7], [6, 8, 9, 1]]

Now I'd like to remove all null values and the corresponding element from the other array which results in:

[[1, 2, 7], [6, 8, 1]]

I'm able to do that but I'm looking for a solution with _.flow.

Approach

This is my approach that doesn't return an array of arrays and also doesn't remove the element from the other array.

_.flow([
      xorWith(_.isNull)
])([1, 2, null, 7], [6, 8, 9, 1])

1. Update

My input will always be [[ // Elements], [ // Elements]]. It wasn't clear at my approach.


Solution

  • const multiple = [[1, 2, null, 7], [6, 8, 9, 1]];
    const withoutNulls = (arr) => _.every(arr, _.negate(_.isNull));
    
    const result = _.flow(
      _.zip,
      (tuples) => _.filter(tuples, withoutNulls),
      _.unzip 
    )(...multiple)
    
    console.log(result);
    <script src="https://unpkg.com/[email protected]/lodash.js"></script>