Laurim
Laurim

Reputation: 55

Return lengths of strings in Google Apps Script

I'm trying to return the length of strings in a range in Google Sheets.

Here's the test cells:

enter image description here

I have a custom function that should return the length of each string:

function returnLength(array) {
  var returnList = [];
  array.forEach(function(a) {
    returnList.push(a.length);
  });
  return returnList;
}

When I use this function in B1, it returns 1 for the length of any of them:

enter image description here

The thing throwing me off is if I leave off the ".length" in the push to resultArray, it returns the correct strings...

function returnLength(array) {
  var returnList = [];
  array.forEach(function(a) {
    returnList.push(a);
  });
  return returnList;
}

enter image description here

I know I could use LEN() to handle this example, but this is just a tiny part in a really large project where I need to be able to get the length within the code.

Upvotes: 1

Views: 2289

Answers (1)

Tanaike
Tanaike

Reputation: 201358

I think that the reason of your issue is that array is 2 dimensional array like [["This"],["Is"],["A"],["Test"],["Hello"],["World"]]. In the case of returnList.push(a.length);, the length of the array which is the element of the 2 dimensional array is returned. By this, all values are 1. So how about this modification?

From:

returnList.push(a.length);

To:

returnList.push(a[0].length);

Upvotes: 2

Related Questions