TimmyTimmy TimmyTimmy - 3 months ago 9
Javascript Question

Split multiple arrays into strings, skipping empty arrays

I've made an AJAX call that has returned 20 arrays, some of which are empty, and others that have one or more items in them. I've split each array into strings using a for loop. The only problem is that this creates lots of empty strings from the arrays that were empty. Is there a way that I could skip the empty arrays in my for loop?

enter image description here



success: function(data){
console.log(data);
for(x in data.data){
var hashArray = data.data[x].tags;
var hashStrings = hashArray.toString().split(',');
var hashtags = '';

for(var i = 0; i < hashStrings.length; i++) {
hashtags = hashStrings[i];
console.log(hashtags);
}
}
}







Object
attribution
:
null
caption
:
Object
comments
:
Object
created_time
:
"1431210854"
filter
:
"Normal"
id
:
"981390235418259116_4657330"
images
:
Object
likes
:
Object
link
:
"https://www.instagram.com/p/2emTgwJG6s/"
location
:
Object
tags
:
Array[0]
type
:
"image"
user
:
Object
user_has_liked
:
false
users_in_photo
:
Array[1]
__proto__
:
Object
19
:
Object
attribution
:
null
caption
:
Object
comments
:
Object
created_time
:
"1430316366"
filter
:
"Normal"
id
:
"973886728247209194_4657330"
images
:
Object
likes
:
Object
link
:
"https://www.instagram.com/p/2D8NHIpGzq/"
location
:
Object
tags
:
Array[2]
type
:
"image"
user
:
Object
user_has_liked
:
false
users_in_photo
:
Array[0]
__proto__
:
Object




Answer

Check the .length of the array. If it's 0 then it contains no elements, in which case continue to the next loop iteration. EDIT per comments for the array we're testing, seems more likely you'll be testing data.data[x].tags.length:

success: function(data){
  console.log(data);
  for(x in data.data){
    if (data.data[x].tags.length == 0) continue;

    var hashArray = data.data[x].tags;
    var hashStrings = hashArray.toString().split(',');
    var hashtags = '';

    for(var i = 0; i < hashStrings.length; i++) {
      hashtags = hashStrings[i];
      console.log(hashtags);        
    }
  }
 }
Comments