user3498459
user3498459

Reputation:

Why won't the string concatenate in the loop?

 if (y.length==num){
              let m = y.toString();
              let h = "";
              let g = "";
              let n = "";
              for(let j=0;j<m.length;j++){
                n = m.charAt(j);
                if (n!=","){
                  g = h.concat(n);
                }
            }
            console.log(g)
          }

If an array's length is equal to an integer, then we're creating a variable of the string made of out the array as well as an arbitrary string h. Then we're looping through the string m, using charAt. The aim is to get rid of commas in the string and then consolidate chars not equal to a comma. However, the loop won't concatenate the new string. Do you guys happen to have any idea why?

Upvotes: 0

Views: 44

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371198

h is initialized to the empty string, and never gets reassigned, so

var g = h.concat(n);

will always effectively mean

var g = n;

which is the current character being iterated over.

You might remove the g variable entirely, and reassign h instead:

const num = 5;
const y = ['a', 'b', ',', 'c,', 'd'];

if (y.length==num){
  let m = y.toString();
  let h = "";
  for(let j=0;j<m.length;j++){
    let n = m.charAt(j);
    if (n!=","){
      h = h.concat(n);
    }
  }
  console.log(h)
}

A much more readable option would be to join by the empty string (don't invoke toString, that'll add undesirable commas), and then use a regular expression to remove ,s:

const num = 5;
const y = ['a', 'b', ',', 'c,', 'd'];

if (y.length==num){
  const cleaned = y
    .join('')
    .replace(/,/g, '');
  console.log(cleaned);
}

Upvotes: 1

Related Questions