desalwe
desalwe

Reputation: 19

How can I push arrays generated within for loops into an empty array outside the loop?

(I know similar questions have been asked in the past but I can't find a satisfactory answer... sorry!)

Hi all,

I'm using a for-loop within a for-loop, resulting in new arrays.

Each time the inner loop runs, I'd like to push the resulting array into a pre-created empty array. I'm expecting an array of arrays.

When I test by console-logging each of the arrays generated within the inner loop, all the arrays I expect are being created👍. But, weirdly, when I try to .push() each one onto the pre-created empty array, I end up with an array full of index numbers, rather than an array of arrays (???) .

If anyone managed to follow that description, please help!! Thanks very much!

const isColourful = num => {
  const arr = num.toString().split('');

  const blankArr = [];

  const arrayOfArraysMaker = arr => {
    for (let c = 0; c < arr.length; c++) {
      for (let i = 0; i < arr.length; i++) {
        if (i + c > 0) {
          x = i + c;
        } else {
          x = undefined;
        }

        const workingArr = blankArr.push(arr.slice(i, x));
        console.log(blankArr);
      }
    }
  };

  arrayOfArraysMaker(arr);

  return arr;
};

console.log(isColourful(2457));

Returns a list of numbers 1 through 16, when I was expecting an array of the following arrays:

[ '2', '4', '5', '7' ]
[]
[]
[]
[ '2' ]
[ '4' ]
[ '5' ]
[ '7' ]
[ '2', '4' ]
[ '4', '5' ]
[ '5', '7' ]
[ '7' ]
[ '2', '4', '5' ]
[ '4', '5', '7' ]
[ '5', '7' ]
[ '7' ]

Upvotes: 1

Views: 1124

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187134

Your code works, but I think I see what might have you confused.

const workingArr = blankArr.push(arr.slice(i, x));

This line doesn't do what you might be thinking.

Array's push method returns the new length of the array (documentation here)

If you were using the returned value from push then you would get a number increasing by one everytime that push() is called on that array, since the array gets one item longer each time.

You shouldn't use the return value of push() at all here, as it modifies the original array.

Upvotes: 1

Related Questions