LirysJH
LirysJH

Reputation: 214

Losing data from array

I'm slicing 3 elements from an array and storing them to another array

array = [1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1];
rows = 3;

Here is my method

getVertWallStruct = (array, rows) => {
    let i = 1,
        storageArr = [],
        data = [];

    for (let k = 0; k < rows*2; k++) { // everything's ok here
      storageArr.push(array.slice(k*rows, (k+1)*rows));
    }

    data = storageArr;

    console.log("storageArr - ", storageArr, " , array - ", array, " , data - ", data);

    return data;
  }

In this case storageArr will consist of empty arrays (as far as data). But when I delete line with data = storageArr; I get:

storageArr =  [ //storageArr should look like this in the end
  [1, 1, 1],
  [0, 1, 1],
  [1, 1, 1],
  [1, 1, 1],
  [0, 1, 1],
  [1, 1, 1]
]

Why do I lose values?

Update: Even when I copy-pasted code from one of the answers - method returns empty data. Why?

Code looks like:

getVertWallStruct = (array, rows) => {
    console.log(array, rows); //okay here
   
    let iterator = array.values()
    let out = []
    for (let i = 0;i < ~~(array.length / rows); i++){
      out.push([iterator.next().value, iterator.next().value, iterator.next().value])
    }
    console.log(out); //empty ???
    
    return out;
  }

enter image description here

Upvotes: 3

Views: 658

Answers (2)

NVRM
NVRM

Reputation: 13082

A possible way to do that, using an Array iterator:

The values() method returns a new Array Iterator object that contains the values for each index in the array. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values

const array = [1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1]
let iterator = array.values()
let out = []
for (let i = 0;i < ~~(array.length / 3);i++){
  out.push([iterator.next().value, iterator.next().value, iterator.next().value])
}
console.log(out)


Update, this looks to works fine:

Update: Even when I copy-pasted code from one of the answers - method returns empty data. Why?

getVertWallStruct = (array, rows) => {
    let iterator = array.values()
    let out = []
    for (let i = 0;i < ~~(array.length / rows); i++){
      out.push([iterator.next().value, iterator.next().value, iterator.next().value])
    }
    return out;
  };

console.log(
  getVertWallStruct([1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1], 3)
)

Upvotes: 2

Adrian Brand
Adrian Brand

Reputation: 21638

Use a reduce, push a blank array into the accumulator every time the index is divisible by the number of rows. Push the current item into the last array in the accumulator.

const array = [1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1];

const rowify = (array, rows) => array.reduce((results, current, index) => {
  if (index % rows === 0) {
    results.push([]);
  }
  results[results.length - 1].push(current);
  return results;
}, []);

console.log(rowify(array, 3));

Upvotes: 0

Related Questions