Search code examples
javascriptmysqlarrayssubstr

JavaScript getting returned array from function and formatting array items


I was having some problem when trying to get the returned array from function in JavaScript. Here is the code:

var circle;
var eventNameList = [];
function doBuffer(pos) {
$.ajax({
    url: "/TogetherSG/TogetherServlet?action=GetEvents",
    type: "GET",
    data: "",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        $.each(data, function (i, jsondata) {
            showBuffer(p1,p2, eventName, eventDesc, eventVenue);
            getChart();
        });
    },
    error: function (request, state, errors) {
    }
});
}

Basically doBuffer() will get all the events from MySQL and pass each event into showBuffer to perform calculation.

function showBuffer(p1, p2, eventName, eventDesc, eventVenue) {
// Calculation for distance between two points
var distance = (google.maps.geometry.spherical.computeDistanceBetween(p1,
        p2) / 1000).toFixed(2);
    eventNameList.push(eventName);
}
}

For showBuffer, I am calculating each point for the distance. If the distance is less than 1 then I push the point into the array.

Then from the getChart() which I called from the first function above:

function getChart(){
    console.log(eventNameList);
}

I am printing out the list. However, I am getting the result as:

[] events.js:202
[] events.js:202
[] events.js:202
[] events.js:202
[] events.js:202
[] events.js:202
["Event4"] events.js:202
["Event4", "Event5"] events.js:202
["Event4", "Event5", "Event6"] events.js:202
["Event4", "Event5", "Event6", "Event7"] events.js:202
["Event4", "Event5", "Event6", "Event7"] events.js:202
["Event4", "Event5", "Event6", "Event7"] events.js:202
["Event4", "Event5", "Event6", "Event7"] events.js:202
["Event4", "Event5", "Event6", "Event7"] events.js:202
["Event4", "Event5", "Event6", "Event7"] events.js:202
["Event4", "Event5", "Event6", "Event7"] events.js:202
["Event4", "Event5", "Event6", "Event7"] events.js:202
["Event4", "Event5", "Event6", "Event7"] events.js:202
["Event4", "Event5", "Event6", "Event7"] 

I wonder how come it loops so many times. Because from the results returned, I need to format it into a string in this way:

'Event4','Event5','Event6','Event7'

But I not sure when and where should I formatted it. Any ideas?

Thanks in advance.


Solution

  • To get your desired string format of 'Event4','Event5','Event6','Event7' from an array that contains these single words as elements, you can simply join the array elements with ',', and then just add the missing ' in the front and back like so:

    var desiredStringFormat = "'" + yourArray.join("','") + "'";