annonymous 1 February 2016

do make arraylist from the array having value by javascript

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

Answers


Nina Scholz February 2016

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>');


leobelizquierdo February 2016

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>

Post Status

Asked in February 2016
Viewed 2,744 times
Voted 5
Answered 2 times

Search




Leave an answer