2

Right now I am trying to create an array of objects that have numbers greater than 0, and when the number is 0 the array ends , when the number is greater than 0 a new array should be created (therefore the function should return an array of arrays, broken up when there are 0's in the middle.

Input and desired output:

input = [1,2,3,4,0,0,0,9,9,0,0]
output = [[1,2,3,4][9,9]]

My function (so far):

function group(Array) {
  let allArray = []
  let runGroup = new Array()
  Array.forEach(function(runtimeI,index) {
    if (runtimeI > 0)
   { 
      runGroup[i] = new Array()
      runGroup[i].push(runtimeI)
    }


    }
  )
  allArray.push(runGroup[i])

}
 array = [10,0,0,1,1,2,0,0,15,0,0,0,5,5,5,]

console.log(group(array))

The function I created throws an error saying array is not a constructor

working example function (that creates the kind of structure I need)

var squares = new Array();
for(var i = 0; i <= 8; i++)
{
    squares[i] = new Array();
    for(var j = (i * 20) + 1; j <= 20 * i + 20; j++)
        if (squares[i] == null)
            squares[i] = j;
        else
            squares[i].push(j);
}

console.log(squares)

so I guess my question is, is there something about for loops that forEach can't do? is there another way I should be accomplishing this?

9
  • 6
    The .forEach() code you posted has several errors; have you checked the console? Commented Jul 1, 2019 at 14:40
  • Array.forEach? you're just calling a forEach on...nothing in particular. What should this iterate over? Commented Jul 1, 2019 at 14:43
  • 2
    group(Array) that's worse! new Array() now does NOT make a new array but calls new on the input. Commented Jul 1, 2019 at 14:46
  • 2
    Don't shadow the Array constructor function for a start. It can also help to use the array literal initialiser - [] instead of new Array but shadowing Array is still confusing. Commented Jul 1, 2019 at 14:49
  • 1
    function group(Array) { — Don't mask global functions with local variables that have the same name. Don't use variables that start with a capital letter for things that are not constructor functions. Commented Jul 1, 2019 at 14:49

3 Answers 3

2

If you're working with smallish arrays, a combination of joining and splitting is a concise way to filter out the 0's...

let input = [1,27,3,4,0,0,0,9,9,0,0];
let arrays = input.join('&').split('&0');
let output = arrays.filter(a => a).map(s => s.split('&').filter(s => s).map(s => parseInt(s)))
console.log(output);

In English: Join produces a string of all of the input digits. Splitting on '0' produces an array of arrays, empty at the delimiter ('0'). Remove the empty ones and split them again to produce arrays of digits.

Alternatively, probably more appropriate for large arrays, using a more iterative style, as your OP began...

let input = [1, 27, 3, 4, 0, 0, 0, 9, 9, 0, 0];
let output = [];
let runGroup = [];

input.forEach(num => {
  if (num === 0) {
    if (runGroup.length) {
      output.push(runGroup);
      runGroup = [];
    }
  } else {
    runGroup.push(num);
  }
});
console.log(output);

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

5 Comments

what if numbers are greater than 9?
@KamilKiełczewski - agreed. added a non-numeric delimiter.
I would probably be looking at arrays with thousands of values , but I will check into solutions with that in mind. Thank you!
@JasonHarder - edited to approach iteratively for larger arrays.
Thanks @danh !! great answer!
1

You could abuse the split/join method as follow

// Build a string from your initial array
var step1 = input.join('#')
// Remove the '0' and build arrays around it
var step2 = step1.split('#0')
// Filter empty values
var step3 = step2.filter(v => v)
// Build the final result
var output = step3.map(v => v.split('#').filter(s => s))

enter image description here

1 Comment

what if numbers are greater than 9?
0

You have at least one problem in your code - inside Array.forEach you use index i instead of index. As alternative you can use following code

input = [1,2,3,4,0,0,0,9,9,0,0]

output = input.join().replace(/(,0)+/g,'-').replace(/-$/,'')
              .split('-,').map(x=>x.split(',').map(y=>+y))

console.log(JSON.stringify(output));

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.