Question

I think the code will explain it, but I'm trying to slice a jquery object list into an array and then concatenate them onto another array, multiple times. Anyways in the .each function i am getting elements in the lis variable, but when I try to slice and concat them onto the listItemArray, it isn't working. I assume I'm losing scope or there is some binding issue or something, but I can't figure out what it is. Thanks for the help. Also I know there is a jquery.slice method but I wanted to keep it vanilla if possible.

var updateSection7 = function(desired) {

    var section = $('#' + _me.UUID + ' .section7yAxis');
    var showedList = section.find('ul:not(:hidden)');
    var listItemArray = [];
    var _slice = Array.prototype.slice;


    showedList.each(function(ind,el){
        var lis = $(el).find('.control-group');
        if(lis.length>1){               
            listItemArray.concat(_slice.call(lis));             
        }
    });
}

UPDATED: Here I included both the push and concat varieties of solving the problem and did away with some wasted cpu time per requests.

var updateSection7 = function(desired) {

    var lis = $('#' + _me.UUID + ' .section7yAxis ul:not(:hidden) .control-group');
    var listItemArray = [];
    var concatTester = [];
    var _slice = Array.prototype.slice;
    var _push = Array.prototype.push;

    //these end up doing the same thing 
    _push.apply(listItemArray, _slice.call(lis));
    concatTester = concatTester.concat(_slice.call(lis));
}
Was it helpful?

Solution

concat doesn't mutate the original array. It returns the new array.

Try this:

listItemArray = listItemArray.concat(_slice.call(lis));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top