Wrap array operation result string inside another string I'm trying to loop through an array, add " before, ", after each member but ommit the , at the very last member in order to generate a JSON string:

const generate_list_data_attribute = (attribute_name, from_array) =&gt; {
    let string = '';

    from_array.forEach((element, key, array) =&gt; {
        if(Object.is(array.length - 1, key)) {
            string += `"${element}"`
        } else {
            string += `"${element}",`
        }
    });

    return `data-${attribute_name}="[${string}]"`;
}


I don't like the fact that I need to Object.is(array.length-1, key) in order to dictate what the code should do with the last member. It should be automatically handled.

To note: I understand that I can just return to skip the usage of else but I'm looking for a way to automatize that "last member" check more or less.



Input (array): my_array = ["food", "gourmet", "foodie"]

Operation: generate_list_data_attribute('random', my_array);

Output (string): data-random="["food", "gourmet", "foodie"]"
Use JavaScript's array methods to your advantage and solve you problem the functional way:

const generate_list_data_attribute = (attribute_name, from_array) =&gt; {
  const string = from_array.map(element =&gt; `"${element}"`).join(",")
  return `data-${attribute_name}="[${string}]"`
}