Search code examples
javascriptarrayssplice

Nice way to create new arrays from provided array with determined length without start with 0


I think I achieve my goal but I'm sure that it is not the best approach to do it. I have a function and there is a issue that make it to add some extra [0], I got that is because the while test keep going. I don't need to do it with while+splice. I would like some suggestion to make it easier. My goal is from a provided array, create new arrays always starting from a element different from 0 and the length will be provided as k:

function splitNumber(arrayProvided, k) {
  let newArray = [];

  while (arrayProvided.length > 0) {
    newArray.push(
      arrayProvided.splice(
        arrayProvided.findIndex(el => el),
        k
      )
    );
  }
  return newArray;
}

console.log(
  splitNumber([1, 0, 4, 6, 0, 7, 8, 4, 2, 0, 8, 3, 0, 0, 0, 0, 0, 0, 0, 6], 4)
);

The result for this code is:

[
  [ 1, 0 ], [ 4, 6 ],
  [ 7, 8 ], [ 4, 2 ],
  [ 8, 3 ],    [ 6 ],
     [ 0 ],    [ 0 ],
     [ 0 ],    [ 0 ],
     [ 0 ],    [ 0 ],
     [ 0 ],    [ 0 ],
     [ 0 ]
]

It's correctly partially because the system is having a extra working after the job done adding extra [0]. The system cannot start with a 0 value in the first array position and no need extra [0] (It's happens because the logic is not totally right), and Yes the lenght of the new arrays is the k value.


Solution

  • Without zeroes, you could add another check and omit unwanted zeroes.

    This approach does not mutate the given data.

    function splitNumber(array, k) {
        let result = [],
            i = 0;
    
        while (i < array.length) {
            if (array[i] === 0) {
                i++;
                continue;
            }
            result.push(array.slice(i, i += k));
        }
        return result;
    }
    
    console.log(splitNumber([1, 0, 4, 6, 0, 7, 8, 4, 2, 0, 8, 3, 0, 0, 0, 0, 0, 0, 0, 6], 4));