Skip to content

Array de objetos, sort, order, by key

JavaScriptJQuery

 

How to sort alphabetically an array of objects by key in JavaScript

To sort an array of objects by some key, you will need a valid structure in your array, obviously an array of objects can only have objects with at least one key (the one that you want to sort). In this example, we'll have the MyData variable that has the following structure: 

var MyData = [
    { id : 1, name: "Angel Miguel",   city: "Nex Mexico" },
    { id : 2, name: "Michael Rogers", city: "Bogotá"     },
    { id : 3, name: "Steve Rogers",   city: "New York"   },
    { id : 4, name: "Ángel José",     city: "Bucaramanga"},
    { id : 5, name: "Carlos Delgado", city: "Nex Mexico" },
    { id : 6, name: "Jhonny Zapata",  city: "Zacatecas"  },
    { id : 7, name: "Bruce Wayne",    city: "Gotham"     },
    { id : 8, name: "Speedy Gonzales",city: "Nex Mexico" }
];

Create a custom sort Function

you can simply use:

/**
  Function to sort alphabetically an array of objects by some specific key.
  
  @param {String} property Key of the object to sort.
 /
function dynamicSort(property) {
    var sortOrder = 1;

    if(property[0] === "-") {
        sortOrder = -1;
        property = property.substr(1);
    }

    return function (a,b) {
        if(sortOrder == -1){
            return b[property].localeCompare(a[property]);
        }else{
            return a[property].localeCompare(b[property]);
        }        
    }
}

 

 Sort by key in ascending order

// Sort the MyData array with the custom function
// that sorts alphabetically by the name key
MyData.sort(dynamicSort("name"));
// Display data with new order !
console.log(MyData);

object with the new order:

[  
    { "id":4, "name": "Ángel José",     "city":"Bucaramanga" },
    { "id":1, "name": "Angel Miguel",   "city":"Nex Mexico"  },
    { "id":7, "name": "Bruce Wayne",    "city":"Gotham"      },
    { "id":5, "name": "Carlos Delgado", "city":"Nex Mexico"  },
    { "id":6, "name": "Jhonny Zapata",  "city":"Zacatecas"   },
    { "id":2, "name": "Michael Rogers", "city":"Bogotá"      },
    { "id":8, "name": "Speedy Gonzales","city":"Nex Mexico"  },
    { "id":3, "name": "Steve Rogers",   "city":"New York"    }
]

Sort by key in descending order

// Sort the MyData array with the custom function
// that sorts alphabetically in descending order by the name key
MyData.sort(dynamicSort("-name"));
// Display data with new order !
console.log(MyData);

This would output:

[
    { "id" :3, "name" : "Steve Rogers",    "city":"New York"   },
    { "id" :8, "name" : "Speedy Gonzales", "city":"Nex Mexico" },
    { "id" :2, "name" : "Michael Rogers",  "city":"Bogotá"     },
    { "id" :6, "name" : "Jhonny Zapata",   "city":"Zacatecas"  },
    { "id" :5, "name" : "Carlos Delgado",  "city":"Nex Mexico" },
    { "id" :7, "name" : "Bruce Wayne",     "city":"Gotham"     },
    { "id" :1, "name" : "Angel Miguel",    "city":"Nex Mexico" },
    { "id" :4, "name" : "Ángel José",      "city":"Bucaramanga"}
]
Continue reading "Array de objetos, sort, order, by key"

Chart Pie, libreria chartJS

JQuery

 

 

Modo de uso de la libreria y ejemplo de random colors

<div class="containerChart">
    <button id="renderBtn">Graficar</button>
    <canvas id="myChart"></canvas>
</div>

 

function renderChart(data, labels, coloR) {
    var pie = document.getElementById("myChart").getContext('2d');
    var myChart = new Chart(pie, {
        type: 'pie',
        data: {
            labels: labels,
            datasets: [{
                label: 'Servicio Técnico',
                data: data,
                backgroundColor: coloR
            }]
        },
        options: {
            legend: {
                display: true,
                labels: {
                    fontColor: 'rgb(255, 99, 132)'
                }
            }
        }
    });
}

$("#renderBtn").on('click', function () {
    var dynamicColors = function() {
        var r = Math.floor(Math.random()  255);
        var g = Math.floor(Math.random()  255);
        var b = Math.floor(Math.random() * 255);
        return "rgb(" + r + "," + g + "," + b + ")";
    };
    data = [];
    labels =  [];
    coloR = [];
    $.each(dataOper.lineas, function (i,item) {
        for (i=0;i<item.length;i++) {
            labels.push(item[i].lindes);
            data.push(item[i].subtot);
            coloR.push(dynamicColors())
        }
    });
    renderChart(data, labels, coloR);
});

Apache Cordova, dialer, marcar telefono

Apache Cordova

You didn't specify which version of Cordova you are using so I'm going to assume version > 3.

Make sure that InAppBrowser, a plugin since version 3, is installed and then open the link by calling it through Javascript like this:

window.open('tel:12345678', '_system')

_system will open it with the systems own browser which in turn will open the call dialog, if you use it against http://maps.apple.com/ it will open in the maps app and similar for other apps which opens for special urls.

Remarks:

  • As described in the docs of the InAppBrowser plugin the window.open function won't be set automatically. You have to do it your self: window.open = cordova.InAppBrowser.open;. Instead you can directly use cordova.InAppBrowser.open('tel:12345678', '_system');
  • Make sure your number doesn't have any blankspaces in it (the + prefix is okay). For example you could use a function like the following, assuming num is a string.

Function:

function placeCall(num) {
    if (window.cordova) {
        cordova.InAppBrowser.open('tel:' + num.replace(/\s/g,''), '_system');
    }
}
Simulator doesn't support dialer. No need to waste time.
Continue reading "Apache Cordova, dialer, marcar telefono"

JqGrid, busqueda

JQuery

Aqui te dejo una funcion que me permite buscar por cualquier campo mostrado en tu grilla:

definiendo la Grilla y el input de busqueda:

<input type="text" id="#search_cells">
<table id="gridEjemplo"></table>
<div id="pagerEjemplo"></div>

en tu archivo js

        //funcion Buscar
        var timer;
        $("#search_cells").on("keyup", function() {
            var self = this;
            if(timer) { clearTimeout(timer); }
            timer = setTimeout(function(){
                //timer = null;
                $("#gridEjemplo").jqGrid('filterInput', self.value);
            },0);
        });

con esta funcion te buscara por cualquier campo mostrado en tu grid.. espero te sirva..!!

Continue reading "JqGrid, busqueda"

Apache Cordova, mapas, geolocalizacion

JavaScript

 

 

This is what I use:

function (lat, lon) {
    var latLon = lat + ',' + lon;

    if (device.platform.toUpperCase() === "ANDROID") {
        window.open("geo:" + latLon, "_system");
    } else if (device.platform.toUpperCase() === "IOS") {
        window.open("http://maps.apple.com/?sll=" + latLon + "&z=100&t=k", "_system");
    }
}

Note: when opening Apple maps, the sll=... and t=k, which means I'm specifying an exact longitude and latitude, and t=k means I want apple maps to display satellite imagery. Also, I'm only writing for iOS and Android, so if you're using other platforms be sure to check explicitly for each! I'm pretty sure Android's geo: always works as you would expect, but I could be wrong. Remember: test everything on a real device!

Continue reading "Apache Cordova, mapas, geolocalizacion"

Tabulator, busqueda, filtros

JQuery


 

Forma 1 de filtro (probada LinkedMobile)

$("#nav-search-input").keyup(function () {
    table.setFilter("artdes","like", $(this).val());
});

Forma 2 de filtro (aun no probrada)

var filters = [];
 var columns = table.getColumns();
var search = $(this).val();

columns.forEach(function(column){
    filters.push({
        field:column.getField(),
        type:"like",
        value:search,
    });
});

table.setFilters([filters]);