I have a = [1,2,3,4,5]
b = [2,3,5,6,1,7]
c = [1,2,43,67,8,7]
d = []
e = []
f = []
g = [5,8,9,3]
i want x = [a,b,c,g] with use of jquery
2 Answers
A solution in plain javascript with Array#filter():
function clean(array) {
return array.filter(function (a) { return a.length; });
}
var a = [1, 2, 3, 4, 5],
b = [2, 3, 5, 6, 1, 7],
c = [1, 2, 43, 67, 8, 7],
d = [],
e = [],
f = [],
g = [5, 8, 9, 3],
x = clean([a, b, c, d, e, f, g]);
document.write('<pre>' + JSON.stringify(x, 0, 4) + '</pre>');
Comments
Try using JQuery.grep() to filter each array, the first argument is the array to filter, the second is a function to process each item against (the first argument in the function is the item itself and the second is the index), the third argument is used tu invert the filter (optional), so you can select each item that doesn't pass the filter:
var a = [1, 2, 3, 4, 5],
b = [2, 3, 5, 6, 1, 7],
c = [1, 2, 43, 67, 8, 7],
d = [],
e = [],
f = [],
g = [5, 8, 9, 3];
var result = $.grep([a,b,c,d,e,f,g], function(n){return n.length > 0});
document.write('<pre>'+ JSON.stringify(result) +'</pre>')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
2 Comments
leobelizquierdo
Why is not working? JQuery,grep() filter the elements in an array, so you can exclude the empty arrays that you have, this is not what you want?
Mayur Patel
What's wrong with this solution. It's giving you the results without blank array and you want the same. Isn't it?
d,e,f? how should the result look like?