Reputation: 2108
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
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
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
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
Reputation: 1504
Here you have a more declarative example. Hope it helps:
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.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
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
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