Thomas Degroot
Thomas Degroot

Reputation: 524

How do I filter though an i loop of of Arrays

I use the following code to get an loop of Arrays.

let findingArray = this.listNumber[i].GenericQuestions;
for (let k = 0; k < findingArray.length; k++) {
  let listArray = findingArray[k].Finding;
  console.log("listArray", listArray);
}

It returns all finding Arrays as expected.

enter image description here

What I would like to do is filter out all the empty Arrays from the loop.

All searches seem to point me to filtering inside the Array, but not filtering out empty Arrays.

Upvotes: 1

Views: 67

Answers (2)

Thomas Degroot
Thomas Degroot

Reputation: 524

What I ended up doing is using Array.isArray and then finding length. The up voted answer has some really great information and will also upvote, but what worked with my code is

    let findingArray = this.listNumber[i].GenericQuestions;
      for(let k = 0; k < findingArray.length; k++){ 
        let listArray = findingArray[k].Finding;
        if (Array.isArray(listArray) && listArray.length) {
         console.log("listArray", listArray);
        }
      }

Upvotes: 0

n-smits
n-smits

Reputation: 713

Using your code, just put in an if. Empty arrays are those with length of 0.

let findingArray = this.listNumber[i].GenericQuestions;
for (let k = 0; k < findingArray.length; k++) {
  let listArray = findingArray[k].Finding;
  if (listArray.length) { console.log("listArray", listArray); }
  // length of 0 coalesces to false
}

Alternatively, using filter:

Which is better because it's more readable (and thus understandable), shorter to write, and it's not destructive!

So [1, 2, 3].filter(element => { element > 1 }) removes elements that do not satisfy the expression (result is [2, 3]). Supposing you have let list = [ [], [1, 2, 3], [] ]; you can do list.filter(element => { element.length > 0 }). Filtering IS filtering the elements. In your case, the elements are other arrays, but it works the same way.

Do note one thing, filter is a pure, i.e. non-destructive, i.e. non-altering function; meaning it doesn't change the input, but returns a new copy. Perhaps that's what's bothering you. So:

let list = [ [], [1, 2, 3], [] ];
list.filter(element => { element.length > 0 });
console.log(list); // returns the original!

// instead
let newList = list.filter(element => { element.length > 0 });
console.log(newList); // returns the filtered list

And finally to update your full code, you can greatly simplify by doing something like this, which would be the same as your code (depending on some details not visible in your snippet, but generally the point is, try to push for this style):

console.log( listNumber
  .map(i => i.GenericQuestions)
  .map(i => i.Finding)
  .filter(i => i.length) );
// as you can see, each step takes in the the result of previous array
// meaining they're chainable, which is pretty sweet

Upvotes: 3

Related Questions