GhostKU
GhostKU

Reputation: 2108

Remove empty subarrays in Javascript

I have such an object

var data = [[1,2,34,4,5,6],[3,34,5,3,42,4],[,,,,,],[,,,],[,,,,,],[1,1]]

I need to filter it and get such a result:

var data = [[1,2,34,4,5,6],[3,34,5,3,42,4],[1,1]]

I tried to do it with array.filter() but I can't get the right expression.

Upvotes: 1

Views: 1039

Answers (6)

rcoro
rcoro

Reputation: 326

Another alternative could be use reduce and some.

const data = [[1,2,34,4,5,6],[3,34,5,3,42,4],[,,,,,],[,,,],[,,,,,],[1,1]];

const filteredData = data.reduce((accumulator, currentValue) => {
  if(currentValue.some(x => x)){
    accumulator.push(currentValue);
  }
  return accumulator;
}, []);

console.log(filteredData);

Upvotes: 0

Slai
Slai

Reputation: 22876

let arr = [[1],[1,2],[,2],[,,],,[]]

console.log(JSON.stringify( arr.filter(a => 0 in a) ))

console.log(JSON.stringify( arr.filter(a => Object.keys(a).length) )) // to include sparse subarrays

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37755

Using filter and some

let a = [[1,2,34,4,5,6],[3,34,5,3,42,4],[,,,,,],[,,,],[,,,,,],[1,1]]

let final = a.filter(val=> val.some(v => true))

console.log(final)

Upvotes: 2

Nico Diz
Nico Diz

Reputation: 1504

Here you have a more declarative example. Hope it helps:

  • create a function isArrayEmpty(arr) that returns a boolean that is true if an array is empty. To go deeper into detecting empty values in an array (not just falsy) see this stackoverflow thread. Also see Peter's comment.
  • with this function, filter data excluding empty subarrays.

var data = [[1,2,34,4,5,6],[3,34,5,3,42,4],[,,,,,],[,,,],[,,,,,],[1,1]]

var isArrayEmpty = arr => !arr.filter(elem => true).length;

var result = data.filter(subarray => !isArrayEmpty(subarray))

console.log(result)

Upvotes: 0

Mister Jojo
Mister Jojo

Reputation: 22345

it a double filter case: ( and the shortest code ) ;)

var  data = [[1,2,34,4,5,6],[3,34,5,3,42,4],[,,,,,],[,,,],[,,,,,],[1,1]]

var R = data.filter(r=>r.filter(x=>x).length)

console.log( JSON.stringify(R) )

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138437

 const result = array.map(it => it.filter(_ => true)).filter(sub => sub.length)

First of all, remove all the empty slots from the inner arrays, then remove all arrays with length 0.

Upvotes: 2

Related Questions