mvoase
mvoase

Reputation: 574

Javascript not parsing array passed over through function

I have an array which is passed through a function using javascript, I can't see anything wrong with the code but it doesn't pass over the first array correctly so it can be parsed.

The idea is the first array is 56 items, it then calls the parseData function which is supposed to split this array into chunks of 7.

Here is the two functions:

static async validateRowValues() {
    let data = [];
    await cy.get('tr > td > div.dlCell')
      .each(function (row) {
          let d = row.get(0).innerText;
          data.push(d);
      });
    console.log(data);

    let response = await this.parseData(data);

    console.log({response});
}

static async parseData(tData) {
    console.log(tData);
    let array = [];
    let coll_array = [];
    debugger;
    await tData.forEach(async (v, index) => {
        await array.push(v);
        if (index % 6 === 0 && index !== 0) {
            await coll_array.push(array);
            array = [];
        }
    });
    return coll_array;
}

The first console.log within parseData does return the 56 items, however by the time it reaches tData.forEach it has completely lost its data, and the parsing returns an empty array when it returns coll_array.

If anyone has any ideas?

Upvotes: 0

Views: 124

Answers (2)

mvoase
mvoase

Reputation: 574

We have resolved this. It turns out everything in Cypress is a promise so the first function needed to have a .then

 static async validateRowValues() {
    let data = [];
    await cy.get('tr > td > div.dlCell')
      .each(function (row) {
          let d = row.get(0).innerText;
          data.push(d);
      }).then(() => {
        this.parseData(data);
      });  
}

Upvotes: 0

Akki geek
Akki geek

Reputation: 71

As of now I will take it you getting your data fine in array. ex. arr = [1,2,3,.....58]

Use below code to split in chunks of 7

arr = arr.reduce((acc,data,index)=>{
  if(index==0 || index%7==0) acc.push([])
  acc[acc.length-1].push(data)
  return acc
},[])

The above code will return

arr = [ [1,..,7], [8,...14], ....]

Upvotes: 1

Related Questions