mattHunting10 - 2 months ago 10
Javascript Question

Pushing all iterations of a loop into an array

Consider this:

``````//finalArray = [];

//rangeArr = [1,2,3,4,5]

//allMultiplesArr = [[1,2,3,4...100],[2,4,6,8...100],[3,6,9,12...100],[4,8,12,16...100],[5,10,15,20...100]]

for(var m=0;m<allMultiplesArr.length;m++)
{
for(var n =0;n<allMultiplesArr[m].length;n++)
{
for(var l =0;l<=rangeArr.length;l++)
{
if(allMultiplesArr[m][n] % rangeArr[l]  == 0)
{
///finalArray.push(allMultiples[m][n])
}
}
}
}
``````

I have a 2D array
`finalArray`
which holds 5 elements. Each element counts up to 100 by each element of
`rangeArr`
respectively. Then I loop through the outer array, and through each element in the inner array defined by
`allMultiplesArr[m][n]`
.

Then I am aiming to make the statement: if the numbers of each inner array (
`allMultiplesArr[m][n]`
) are evenly divided into ALL elements of
`rangeArr`
(meaning 1,2,3,4,5) THEN push
`allMultiples[m][n]`
into
`finalArray`
.

What my code currently does, is that it pushes every single number that is evenly divided by ANY of the elements in
`rangeArr`
, and I want it to ONLY push those numbers that are evenly divided by all elements of
`rangeArr`
into
`finalArray`
meaning push ONLY the numbers that are evenly divided by 1 & 2 & 3 & 4 & 5. Which essentially gives me the common multiples of these numbers, up to the number 100.

Use javascript every function to check weather all elements match the condition.

``````for(var m=0;m<allMultiplesArr.length;m++) {

for(var n =0;n<allMultiplesArr[m].length;n++) {

var valid = rangeArr.every(function(range){
return (allMultiplesArr[m][n] % range  == 0)
});

if(valid) {
finalArray.push(allMultiplesArr[m][n])
}
}
}``````