0

This is just a simple javascript exercise that I'm working on.

I'm trying to convert this array...

var array = [
[1,2],
[3,4],
[5,6]
];

into...

array = [1, 2, 3, 4, 5, 6];

by using this nested for loop.

var series;
var storage = [];
for (var i = 0; i < array.length; i++) {
    for (var j = 0; j < array[i].length; j++) {
        series = array[i][j];
        for (var k = 0; k < 6; k++) {
            storage[k] = series;
        };
    };
};

console.log(storage);

With an output of...

//Output: [6, 6, 6, 6, 6, 6]

Why is this the output and how can I fix it?

8 Answers 8

2

for (var k = 0; k < 6; k++) { is not required . array[i] will be each of element inside main array , so iterating over array[i] you can access each of the element

var array = [
  [1, 2],
  [3, 4],
  [5, 6]
];


var series;
var storage = [];
for (var i = 0; i < array.length; i++) {
  for (var j = 0; j < array[i].length; j++) {
    storage.push(array[i][j])
  };
};

console.log(storage);

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

Comments

2
    series = array[i][j];
    for (var k = 0; k < 6; k++) {
        storage[k] = series;
    };

Seriously, here you set the same value to each element of the resulting array.

You probably need something like

for(let x of array) {
    for(let y of x) {
        storage.push(y)
    }
}

Or, if your JS machine is experimental enough, simply

var storage = array.flat()

Comments

1

You can use a mix of reduce and concat to achieve what you want in one line

var array = [
  [1, 2],
  [3, 4],
  [5, 6]
];

console.log(array.reduce((a, v) => a.concat(v), []));

As for why your code didn't work, it's mainly down to this bit

for (var k = 0; k < 6; k++) {
    storage[k] = series;
};

It would overwrite everything in the array with the last value of series, which in your case would be 6

Comments

1

Array.concat can do this on its own

var merged = [].concat.apply([], array);

Comments

1

var array = [
[1,2],
[3,4],
[5,6]
];
var newArray = [];
for (let i = 0; i < array.length; i++) {
   newArray = newArray.concat(array[i]); 

}
console.log(newArray)

Comments

0

You can use array.flat()

Reference : flatten

var array = [
  [1,2],
  [3,4],
  [5,6]
];
array.flat();
// 1,2,3,4,5,6....

Comments

0

You could use the ES6 spread syntax like this:

for (let element of array){
    storage.push( ... el )
}

Comments

0
storage = [];
for(var i=0; i<array.length; i++)
    storage = storage.concat(array[i]);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

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.