Search code examples
javascriptarraysajaxgist

Same Array Different Results


The function closest in the script tags, finds a number closest to 112. However when I use this same function on an identical array from an ajax request, it gives the wrong result.

Console log 1: The local array produces the correct result 122.

Console log 2: External array2 shown to be identical to the local one.

Console log 3: Using the external array results in a left bracket. Removing the brackets from the gist results in 8, which is still incorrect.

JSFiddle

function loadgist(gistid, filename)
{
    $.ajax({
        url: 'https://api.github.com/gists/' + gistid,
        type: 'GET',
        dataType: 'jsonp'
    }).success(function(gistdata) {
        var content = gistdata.data.files[filename].content;
        DoSomethingWith(content)
    }).error(function(e) {
        // ajax error
    });        
}

function DoSomethingWith(content)
{
    number = 112;
    var array2 = (content);
    console.log(content);
    console.log(closest(number, array2));
}

loadgist("9544dfd755418e819810312488e7986c", "gistfile1.txt");
<script src=https://code.jquery.com/jquery-1.9.1.js></script>
<script language="javascript">

function closest(num, arr)
{
    var curr = arr[0];
    var diff = Math.abs (num - curr);

    for (var val = 0; val < arr.length; val++)
    {
        var newdiff = Math.abs (num - arr[val]);

        if (newdiff < diff)
        {
            diff = newdiff;
            curr = arr[val];
        }
    }

    return curr;
}

array = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];
number = 112;
console.log(closest (number, array));

</script>


Solution

  • If you add console.log(typeof content) inside the method DoSomethingWith(...) you will note that the content is not an array, instead it is a string. So use JSON.parse() to get an array from the string, like this:

    function DoSomethingWith(content)
    {
        let number = 112;
        let array2 = JSON.parse(content);
        console.log(content);
        console.log(closest(number, array2));
    }