Behseini
Behseini

Reputation: 6320

Append Comma on Converting Array elements to String

Can you pleas take a look at this demo and let me know how I can append , between elements of an array from the current output of

p[data-st!=all]p[data-st!=men]p[data-st!=bi]

To

p[data-st!=all], p[data-st!=men], p[data-st!=bi]

var filters = ['all',null,'men','bi',null];
var text = '';
var i;
for (i = 0; i < filters.length; i++) { 
if(filters[i]!= null){
  text += "p[data-st!="+filters[i]+"]";
}
    
}
console.log(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Views: 63

Answers (5)

malik kurosaki
malik kurosaki

Reputation: 2042

var filters = ['all',null,'men','bi',null];
var a = [];
for(i in filters){
 if(filters[i]!= null){
  var b = [];
  b = "p[data-st!="+filters[i]+"]";
  a.push(b); 
 }
}
console.log(a.join());

Upvotes: 0

Facundo Larrosa
Facundo Larrosa

Reputation: 3389

var filters = ['all',null,'men','bi',null];
var text = '';
var i;
for (i = 0; i < filters.length; i++) { 
if(filters[i]!= null){
  text += (i===0?"":", ") + "p[data-st!="+filters[i]+"]";
}
    
}
console.log(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Here's anotehr solution as well. You coul've pushed each p bracket to an array and join them. If you're not too worried about memory and iterations. Hear's a clean and easy to read solution. If you're not already familiar, it'll introduce you to two useful array methods.

function parseString(word)
{
  return `p[data-st!=${word}]`
}

var filters = ['all',null,'men','bi',null];
let text = filters
.filter(val => !!val)
.map(val => parseString(val))
.join(',');

console.log(text);

Upvotes: 1

Tyler Roper
Tyler Roper

Reputation: 21672

You could complete this (and clean up a bit) using array methods.

var filters = ['all',null,'men','bi',null];

var result = filters
                 .filter(n=>n)
                 .map(n => "p[data-st!="+n+"]")
                 .join(", ");

console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

brk
brk

Reputation: 50291

Create a new array variable and push the modified by adding p[data-st! text to it and then use join method with comma(,) as delimiter to join the elements

var filters = ['all', null, 'men', 'bi', null];
var inArray = []
var i;
filters.forEach(function(item) {
  if (item !== null) {
    inArray.push("p[data-st!=" + item + "]")
  }
})
console.log(inArray.join(','));

Upvotes: 0

Eddie D
Eddie D

Reputation: 1120

You can do a simple for loop over the string and add a coma after every right facing bracket. Not the best option but it'll work.

var newString = '';
for(let i = 0; i < text.length; i++)
{
  let char = text[i];
  newString += char;
  if(char === ']') newString += ',';
}

Upvotes: 0

Related Questions