Split Array Using Null Separator

Is there any way to split an array into arrays that don't contain null values ​​using javascript (without function development) ...

Here is an example of what I want to have:

:

var a = [1, 2, 3, null, 2, null,null, 4] 

output:

 [[1, 2, 3], [2], [4]] 

thanks

+2
source share
3 answers

To the question

"Is there a ready-made function to create my array",

answer

" No , because your need is too specific."

But this is not so difficult to do yourself. Here's the solution (I made a less trivial input with null at the ends and consecutive null more indicative):

 var a = [null, 1, 2, 3, null, 2, null, null, 4, null]; var b = []; // result for (var arr, i=0; i<a.length; i++) { if (a[i]===null) { arr=null; } else { if (!arr) b.push(arr=[]); arr.push(a[i]); } } document.body.textContent = JSON.stringify(b); // just print the result 

As you can see, there is nothing pretty or magical, just a tedious iteration.

+3
source

You can use reduce :

 [1, 2, 3, null, 2, null, 4].reduce(function(arr, val) { if(val === null) arr.push([]); else arr[arr.length-1].push(val); return arr; }, [[]]); 
+2
source

There is no function in the library that does what you expect. But if you just approach it, you can use the following approach

 var a = [1, 2, 3, null, 2, null, 4] var result = [], temp = []; for(var i = 0; i < a.length; i++) { if (a[i] === null) { if (temp.length == 0) continue; result.push(temp); temp = []; } else { temp.push(a[i]); } } if (temp.length != 0) result.push(temp); // use your result, it gives [[1, 2, 3], [2], [4]] 

I added some functions to prevent problems with double null , starting with null and ending with null . The next step is to simply wrap the above snippet in a function, using a as an argument and result as the return value. It even handles a = [] without any problems.

+1
source

All Articles