1

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.

3
  • 2
    ; i < ary.length / splitLength; Commented Dec 31, 2016 at 3:48
  • stackoverflow.com/questions/35310865/… (duplicate)? Commented Dec 31, 2016 at 3:49
  • or simply later do console.log(outer_lis .filter(String) );, which skips empty arrays Commented Dec 31, 2016 at 3:52

4 Answers 4

2

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 ] ]
Sign up to request clarification or add additional context in comments.

Comments

1
var arr = [[1,2,3],[],[3,4,5]];
var newArr = arr.filter(function(item){
  return item.length !== 0;
});

Comments

0

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

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.