I have an array outer_array. I try to push some array inside the outer_array. But some of the pushed array are empty. I don't want those empty array. I can remove it manually, but i need to delete it from the loop. here is my code:
var ary = [1, 2, 3, 4, 5, 6];
var splitLength = 3;
var outer_lis = [];
var first_limit = 0;
var second_limit = splitLength;
for (var i=0; i<ary.length; i++) {
outer_lis.push(ary.slice(first_limit, second_limit));
first_limit += splitLength;
second_limit += splitLength;
}
console.log(outer_lis);
// Result
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [], [], [], [] ]
I searched for a solution but i got results in php. I dont understand php. If you can give me a solution for this problem its much appreciated. because i am a beginner in Javascript.
4 Answers 4
Thanks to dandavis I got the solution. I change the code like this:
...
for (var i=0; i < ary.length / splitLength; i++) {
outer_lis.push(ary.slice(first_limit, second_limit));
first_limit += splitLength;
second_limit += splitLength;
}
...
Now i got the result as i expected.
// Result
[ [ 1, 2, 3 ], [ 4, 5, 6 ] ]
Comments
var arr = [[1,2,3],[],[3,4,5]];
var newArr = arr.filter(function(item){
return item.length !== 0;
});
Comments
Try this , it will help you to achieve your result without empty array. in this code you can change your splitLength value also.
var ary = [1, 2, 3, 4, 5, 6];
var splitLength = 3;
var outer_lis = [];
var first_limit = 0;
var second_limit = splitLength;
var looplimit = Math.ceil(ary.length / splitLength);
alert(looplimit);
for (var i = 0; i < looplimit; i++) {
outer_lis.push(ary.slice(first_limit, second_limit));
first_limit += splitLength;
second_limit += splitLength;
}
console.log(outer_lis);
Comments
The solution is simple. Here is the code
var ary = [1, 2, 3, 4, 5, 6, 4],
splitLength = 3,
outer_lis = [],
first_limit = 0,
second_limit = splitLength,
length = ary.length,
totalSubArrays = Math.ceil(length/splitLength);
for (var i = 0; i < totalSubArrays; i++) {
outer_lis.push(ary.slice(first_limit, second_limit));
first_limit += splitLength;
second_limit += splitLength;
}
console.log(outer_lis);
; i < ary.length / splitLength;console.log(outer_lis .filter(String) );, which skips empty arrays