1

As the title suggests I'm trying to remove the last "," that appears when i return my function relative to a specific inputted name: For example I'm getting the following returned: "cat,bird,tiger, " when I'm trying to return "cat,bird,tiger " i have tried string = string.replace(/,\s*$/, ""); but this replaces all commas. here is my current code.

let string = "";

for(let i = 0; i < result.length; i++) {
  console.log(result[i].animal)
  string = string + result[i].animal + ",";
}
if(string != ""){
console.log(string);
}
else{
  console.log("NOT FOUND");
}

2 Answers 2

3

Map the array to the animal properties, then join by a comma instead:

const string = result.map(({ animal }) => animal).join(',');

To tweak your original code, add a comma to the beginning of the concatenated string if string is not empty:

let string = '';
for(let i = 0; i < result.length; i++) {
  string += (string ? ',' : '') + result[i].animal;
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you so much, the tweaked code worked. As a beginner can you explain what the code in the parenthesis is doing exactly and give it some context on how that did what i was after?
It destructures the animal property from the object being iterated over and extracts only that value from every object, creating a new array. It's like .map(r => r.animal). Then all you need to do is join the array of strings.
0

i use this code for everywhere i want have like this string

 item,item,item,item,....,item

in first time i didn't add any comma and after then first add comma and then add item

if(string!=""){
        string+=","
      }

let string = "";

for(let i = 0; i < result.length; i++) {
  if(string!=""){
    string+=","
  }
  console.log(result[i].animal)
  string = string + result[i].animal ;
}
if(string != ""){
console.log(string);
}
else{
  console.log("NOT FOUND");
}

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.