Published By - Rajendra Nagar

How to remove trailing commas from the last element of an array using JavaScript?

Use the replace() function to target and remove the unwanted comma effectively. This approach is particularly useful in scenarios like JSON formatting or cleaner data output. Optionally, transform the string back into an array if needed.

Rajendra Nagar

To remove the comma from an array's last element, call the replace() method.

let array = ['value1', 'value2', 'value3', 'value4', 'value5,'];
let last_index = array.length-1;
let last_value = array[last_index].replace(',', '');
array[last_index] = last_value;
console.log(array);
//Output
['value1', 'value2', 'value3', 'value4', 'value5']

  • Find the last element from an array using length.

    array.length-1;

  • Replace comma using the replace method and filter new value

    array[last_index].replace(',', '');

  • Push new value at last element index

    array[last_index] = last_value;

Output will be
//Output
['value1', 'value2', 'value3', 'value4', 'value5']