Search code examples
javascriptlodash

Javascript/lodash how to remove empty arrays


I'm working with this structure:

[
   [
      {
         "comments":"asd",
         "movement":"Back Squat",
         "userID":"wDHZv3OL55SIymHkhMUejNleNkx1",
         "weight":"330"
      }
   ],
   [
      {
         "comments":"asd",
         "movement":"Bench Press",
         "userID":"wDHZv3OL55SIymHkhMUejNleNkx1",
         "weight":"100"
      }
   ],
   [
      {
         "comments":"Comment",
         "movement":"Clean",
         "userID":"wDHZv3OL55SIymHkhMUejNleNkx1",
         "weight":"195"
      }
   ],
   [

   ],
   [

   ],
   [
      {
         "comments":"Front squat comment alpha",
         "movement":"Front Squat",
         "userID":"wDHZv3OL55SIymHkhMUejNleNkx1",
         "weight":"315"
      }
   ],
   [

   ],
   [

   ],
   [

   ],
   [

   ],
   [

   ],
   [
      {
         "comments":"abc",
         "movement":"Strict Press",
         "userID":"wDHZv3OL55SIymHkhMUejNleNkx1",
         "weight":"155"
      }
   ]
]

This is the input I'm using in JSON format. As you can see there are multiple empty arrays.

How would I go about filtering through these arrays and remove the empty ones?


Solution

  • Use the native Array#filter or lodash's _.filter(), and keep the sub arrays with length other than 0.

    Array#filter

    var arrs = [[{"comments":"asd","movement":"Back Squat","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"330"}],[{"comments":"asd","movement":"Bench Press","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"100"}],[{"comments":"Comment","movement":"Clean","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"195"}],[],[],[{"comments":"Front squat comment alpha","movement":"Front Squat","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"315"}],[],[],[],[],[],[{"comments":"abc","movement":"Strict Press","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"155"}]];
    
    var result = arrs.filter(function(sub) {
      return sub.length;
    });
    
    console.log(result);

    Lodash's _.filter() with _.size:

    var arrs = [[{"comments":"asd","movement":"Back Squat","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"330"}],[{"comments":"asd","movement":"Bench Press","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"100"}],[{"comments":"Comment","movement":"Clean","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"195"}],[],[],[{"comments":"Front squat comment alpha","movement":"Front Squat","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"315"}],[],[],[],[],[],[{"comments":"abc","movement":"Strict Press","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"155"}]];
    
    var result = _.filter(arrs, _.size);
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>