user13849624
user13849624

Reputation:

Filtering out empty strings from nested arrays

I have an array of arrays like this:

let arr = [
      ["do you ever", "have you ever", "worried"],
      ["another", ""],
      ["about"],
      ["the notion"],
      ["that"],
      ["did you ever"],
      [""]
];

I need to remove empty strings from the nested arrays and nested arrays that became empty as a result. e.g.,

[ ["do you ever", "have you ever", "worried"],
  ["another"],
  ["about"],
  ["the notion"],
  ["that"],
  ["did you ever"]
];

Upvotes: 0

Views: 139

Answers (4)

Mamun
Mamun

Reputation: 68923

You can try using Array.prototype.map() and Array.prototype.filter() like the following way:

let arr = [
      ["do you ever", "have you ever", "worried"],
      ["another", ""],
      ["about"],
      ["the notion"],
      ["that"],
      ["did you ever"],
      [""]
];
arr = arr.map(i => i.filter(i => i.trim())).filter(i => i.length);
console.log(arr);

Upvotes: 3

Tugay İlik
Tugay İlik

Reputation: 3788

By the combination of map and filter, you can achieve that;

I assume the arr only contains arrays and that arrays contain strings. Otherwise, there should be a type check.

let arr = [
  ["do you ever", "have you ever", "worried"],
  ["another", ""],
  ["about"],
  ["the notion"],
  ["that"],
  ["did you ever"],
  [""]
];

arr.map(items => items.filter(_item => _item.length > 0)).filter(i => i.length > 0);

Upvotes: 0

customcommander
customcommander

Reputation: 18921

As I understand it all your arrays (parent and sub arrays) can reduce in size. Using Array#filter alone is impossible and Array#map isn't going to reduce the size of an array.

You can use either Array#reduce or Array#flatMap for this.

I'd go for the latter in this case. It allows you to unnest sub arrays produced during an iteration. This means that you can grow an array with Array#flatMap:

[1, 2].flatMap(n => [n, n]);
//=> [1, 1, 2, 2]

Meaning you can empty an array too:

[1, 2].flatMap(n => []);
//=> []

Both examples cannot be done with Array#map.

So we can use to both transform the elements of an array and transform the array itself (i.e. size gets bigger or smaller):

const xs = [
      ["do you ever", "have you ever", "worried"],
      ["another", ""],
      ["about"],
      ["the notion"],
      ["that"],
      ["did you ever"],
      [""]
];

console.log(

  xs.flatMap(ys => {
    const zs = ys.filter(y => y !== "");
    return zs.length > 0 ? [zs] : [];
  })

)

Upvotes: 1

Ketan Ramteke
Ketan Ramteke

Reputation: 10675

Here is another implementation:

let arr = [
      ["do you ever", ,"","have you ever", "worried"],
      ["another", ""],
      ["about"],
      ["the notion"],
      ["that"],
      ["did you ever"],
      [""]
];
arr = arr.map(a => a.filter(e => e !== "")).filter(e=> e.length !== 0)
console.log(arr)

Upvotes: 1

Related Questions