Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 321
Joe Berthelot Avatar asked Jun 17 '17 08:06

Joe Berthelot


1 Answers

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>
like image 54
Ori Drori Avatar answered Oct 22 '22 01:10

Ori Drori