2
var place = []

place[0] = "Sant Marti de Canals";
place[1] = "Catalonia";
place[3] = "";
place[4] = "Spain";

placeTitle = place.join(",");

current output is "Sant Marti de Canals,Catalonia,,,Spain"

how can it be "Sant Marti de Canals,Catalonia,Spain"

3 Answers 3

3

You can also define a filter function, which is useful in many other situations.

Array.prototype.filter = function(p) {
    var a = [];
    p = p || function (x) {return x;}
    for (var i = 0; i<this.length; ++i) {
        if (p(this[i])) {
            a.push(this[i]);
        }
    }
    return a;
}

...

placeTitle = place.filter().join(', ');
Sign up to request clarification or add additional context in comments.

1 Comment

I don't need to. The empty string gets converted to false, so it isn't included in the result array. What I don't account for (since it isn't necessary in this case) is 0, which (were it present) would also be filtered out.
2

Writing your own code for this can help

var place = []

place[0] = "Sant Marti de Canals"; place[1] = "Catalonia"; place[3] = ""; place[4] = "Spain";

var placeTitle ='';
for(var test in place) {
    placeTitle += place[test]!=''?place[test]+',':'';
}
placeTitle = placeTitle.substr(0,placeTitle.length-1)

1 Comment

and then remove the , at the end.
0
placeCopy=[];
for(var i=0;i<place.length;i++){
  if(typeof place[i] != 'undefined' && place[i].length > 0){  
    placeCopy.push(place[i]);
  }
}
placeTitle = placeCopy.join(",");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.