N.O.Davis
N.O.Davis

Reputation: 513

Google Script: forEach to Array

I'm trying to push the returned values from forEach to an array.

Right now results are returned individually in the Logger like

result 1 result 2

That's what I want, I just don't know how to get those results back to a single array that I can use outside of the forEach function (as this function is part of a larger one).

Any tips? I looked HERE and attempted to work from that below. The other results I found here were about PHP, which I don't understand.

urls.forEach(function(urlTest) {
    var htmls = UrlFetchApp.fetch(urlTest).getContentText();
    var reg = /text1boldblack\"\>U(.*?)\<\/div/g;
    var reg2 = /text1boldblack\"\>|\<\/div/g;
    var extract = htmls.match(reg);
    var string = String(extract);
    var listDivName = string.replace(/text1boldblack\"\>|\<\/div/g,'');

    var array = [];
    for (var i = 0; i < listDivName.length; ++i) {
    array.push(i);
    Logger.log(array);
    }

Below is an example of what Logger.log(array); currently returns which is obviously more than the two results I was expecting.

[18-12-30 17:05:13:597 EST] U09 Girls 1 - Fall 2018
[18-12-30 17:05:13:597 EST] [0.0]
[18-12-30 17:05:13:598 EST] [0.0, 1.0]
[18-12-30 17:05:13:599 EST] [0.0, 1.0, 2.0]
[18-12-30 17:05:13:599 EST] [0.0, 1.0, 2.0, 3.0]
[18-12-30 17:05:13:600 EST] [0.0, 1.0, 2.0, 3.0, 4.0]
[18-12-30 17:05:13:600 EST] [0.0, 1.0, 2.0, 3.0, 4.0, 5.0]
[18-12-30 17:05:13:601 EST] [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
[18-12-30 17:05:13:602 EST] [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]
[18-12-30 17:05:13:602 EST] [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]
[18-12-30 17:05:13:603 EST] [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
[18-12-30 17:05:13:604 EST] [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
[18-12-30 17:05:13:604 EST] [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0]
[18-12-30 17:05:13:605 EST] [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0]
[18-12-30 17:05:13:606 EST] [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0]
[18-12-30 17:05:13:606 EST] [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0]

Upvotes: 1

Views: 2184

Answers (1)

CaKa
CaKa

Reputation: 3779

"I'm trying to push the returned values from forEach to an array."

ForEach has no return value, but map has!

Map acts like forEach but the return value creates a new array.

const resultArray = urls.map(function(urlTest) {
    var htmls = UrlFetchApp.fetch(urlTest).getContentText();
    var reg = /text1boldblack\"\>U(.*?)\<\/div/g;
    var reg2 = /text1boldblack\"\>|\<\/div/g;
    var extract = htmls.match(reg);
    var string = String(extract);
    var listDivName = string.replace(/text1boldblack\"\>|\<\/div/g,'');

    return listDivName;
}

// do sth with the array:
console.log(resultArray);

Upvotes: 3

Related Questions