jQuery addClass example

Change class name on click in jQuery

by ibroom

HTML

<label for="countries">
  Introduce a Json array with countries that you want to visit: (if you use a key, value pleas name the key as country)
</label>
<br>
<textarea type="number" 
          id="countries"></textarea>
<br>
<button >Send</button>

JavaScript

function validateArray( countries ) {
    return new Promise((resolve, reject) => {
        if(!isValidJson(countries))
            reject("The format is not correct");
        countries = JSON.parse(countries);
        if(typeof countries[0] == "object"){
            countries.sort(complexArray);
        } else if(typeof countries[0] == "number"){
            countries.sort( (a, b) => {return a - b})
        }else {
            countries.sort();
        }
        resolve(countries);
    })

}

function complexArray(a, b)  {
    return ((a['country'] === b['country']) ? 0 : ((a['country'] > b['country']) ? 1 : -1));

}

function isValidJson(json) {
    try {
        JSON.parse(json);
    } catch(e) {
        return false;
    }
    return true;
}

$(document).ready( () => {
    $("button").click( () => {
        validateArray($('#countries').val()).then(
            (result) => {
                console.log(result);
            },
            (error) => {
                console.log(error)     
            }
        )
    })
});