简体   繁体   中英

Why does this work in a for loop but not forEach? (array is not a constructor error)

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?

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

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

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM