shumway21
shumway21

Reputation: 79

Removing commas from multidimensional arrays

I'm having a bit of trouble removing commas from an array when I go to write it to a cell in google spreadsheets. array.join(''); doesn't seem to do the trick. I would appreciate any help. Also, anchor[i][j].join('') returns an error.

Here is a bit of code:

anchor[i][j].join('') returns an error

anchor[i].join('') doesn't seem to have an effect.

for (var i=0; i(less than) rangeKW.length-2;i++){

anchor[i] = [];

   for (var j=0; j<rangeURL.length;j++){

     anchor[i][j] = ahref + rangeKW[i] + ahref1 + rangeURL[j] + "</a>|";      

    }       
  }    
 cell.setValue("{" + anchor);      
}

Upvotes: 0

Views: 2293

Answers (2)

Corey G
Corey G

Reputation: 7858

Suppose you have

  var x = [[1,2,3],[4,5,6]]

Then either of these lines will give you "123456":

  Array.prototype.concat.apply([], x).join('')
  x.map(function(a){ return a.join(''); }).join('');

The first one constructs the array [1,2,3,4,5,6] and then joins it. The second one joins each inner array first, constructing ["123", "456"] and then joins that. I think the first one is likely to be a tiny bit more efficient, although we are talking peanuts here, but the second one gives you a bit more control if you want to put something different between rows and columns.

In both cases, this doesn't change the original value in x. You can assign the new value to x if that's what you want.

Upvotes: 1

Serge insas
Serge insas

Reputation: 46802

array.join() works with "normal" arrays, by normal I mean 1 dimension and applies to the array itself, not on an single element (error on [i][j]), beside that I don't really understand what you want to do and how your code is related to your question ...

concerning anchor[i].join('');// doesn't seem to have an effect. I don't know how many elements are in there and how they look like but the syntax is correct. You can also use toString() if you want to make it a CSV string.

EDIT : (thanks for the information in comments.)

I think the easiest way (or at least the most clear) would be to create a couple of new variables that you could log separately to see exactly what happens.

for example

var anchorString = anchor[i].join(); // or toString() they both return strings from 1D arrays
Logger.log(anchorString) 

if every index i of anchor have to be in the same cell then write it like this in the i-loop :

var anchorString += anchor[i].join(); 
Logger.log(anchorString) 

Upvotes: 0

Related Questions