3

Is there a method to split an array into arrays that dont contain null values using javascript (without developing a function)...

Here is an example of what I want have :

input :

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

output :

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

Thank you

5
  • Have you tried to loop over array and create sub arrays? Commented Dec 29, 2015 at 15:04
  • I know I can, but I'm asking if there is a ready method for use ... without developing a function Commented Dec 29, 2015 at 15:05
  • Looping is done in about 3 lines and there's no reason there would be a generic solution to this very specific problem. Commented Dec 29, 2015 at 15:06
  • Ok, that's fine so ... (the split function for strings is awesome -- I hoped there is one for arrays) ... Thank you Commented Dec 29, 2015 at 15:08
  • 1
    A loop is the best you can do Commented Dec 29, 2015 at 15:27

4 Answers 4

4

To the question

"Is there a ready to use function to build my array",

the answer is

"No, because your need is too specific".

But it's not so hard to do it yourself. Here's a solution (I took a less trivial input with null at ends and consecutive null to be more demonstrative):

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's nothing pretty or magical, just a tedious iteration.

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, Thanks Denys, this works .. but my question is about if there is a method ready for use or not ... However I know that we can develop a function :) ... thank you for your help
Thank you Denys .. I took your answer as the accepted one :)
using slice would be faster I think
@CodeiSir depending on the input, it would probably be faster, yes, but push is already fast (especially on homogeneous arrays) so I doubt it really matters (but I agree it could be faster).
2

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;
}, [[]]);

6 Comments

that's the general idea but this doesn't handle painful cases like a null at the begining or two consecutive null.
@DenysSéguret "_".split("_") is ["",""]. Similarly, my code returns [ [],[] ] for [null].
Also, this function is not good, for example if I have in input : [1, 2, 3, null, 2, null,null,null, 4]
@taboubim If that's the case, you need to make your question clearer about possible inputs and expected outputs, though if you do, you may invalidate this answer. A better approach may be to take this as an answer to the question asked, and see if you can tweak it to suit your actual needs.
@DenysSéguret "123_2___4".split("_") is ["123","2","","","4"]. Similarly, my code returns [[1,2,3],[2],[],[],[4]] for [1,2,3,null,2,null,null,null,4].
|
1

There is no function in the library which does what you expect. But if you approach it simply, you can use the next 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 have added some functionalities to prevent problems with double null, starting null and ending null. The next step is just wrapping the above snippet in a function, using a as argument and result as return value. This even handles a = [] without problems too.

Comments

0

I needed this function, and using .push() isn't going to be fast enough. Here's one using .slice(), as coderPi pointed out.

function split(arr, separator = null) {
  const chunks = [];
  let i = 0, j = 0;
  while (j++ < arr.length) {
    let nextIndex = arr.indexOf(separator, i);
    if (nextIndex === -1) {
      chunks.push(arr.slice(i, arr.length));
      return chunks;
    } else if (nextIndex !== i) {
      chunks.push(arr.slice(i, nextIndex));
    }
    i = nextIndex + 1;
  }
  return chunks;
}

// example:

const myChucks = split([1, 2, 3, null, 2, null, null, 4]);

// returns: [[1,2,3],[2],[4]]

document.write(JSON.stringify(myChucks))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.