javascriptarrayslinq.js

linq,js GroupBy coordinates(lat, lng)


I have the following array:

var coord = [
{flat:"7", house:"14", indication1: "60", lat: "47.93896450", lng:"33.43282100"},
{flat:"9", house:"18", indication1: "65", lat: "47.87736800", lng:"33.27488850"},
{flat:"10", house:"14", indication1: "24", lat: "47.93896450", lng:"33.43282100"},
{flat:"11", house:"14", indication1: "11", lat: "47.93896450", lng:"33.43282100"},
{flat:"12", house:"14", indication1: "56", lat: "47.93896450", lng:"33.43282100"}];

I want to use linq.js to group these array by two fields: lat and lng.

var h = Enumerable.From(data).GroupBy(
            "{lat: $.lat, lng: $.lng}",
            "{ House: $.house, Flat: $.flat }",
            "{ Qlat: $.lat, Qlng: $.lng, info: $$.ToArray()}").ToArray();

console.log(h);

I expected to see 2 groups, but got all 5. Where was I wrong?


Solution

  • You use an object for grouping. Every new generated object is a new object and not equal to the last or any other object.

    You could take null as first parameter and the string with grouping information as fourth parameter.

    var coord = [{ flat: "7", house: "14", indication1: "60", lat: "47.93896450", lng: "33.43282100" }, { flat: "9", house: "14", indication1: "65", lat: "47.87736800", lng: "33.27488850" }, { flat: "10", house: "14", indication1: "24", lat: "47.93896450", lng: "33.43282100" }, { flat: "11", house: "14", indication1: "11", lat: "47.93896450", lng: "33.43282100" }, { flat: "12", house: "14", indication1: "56", lat: "47.93896450", lng: "33.43282100" }],
        grouped = Enumerable.From(coord).GroupBy(
            null,
            "{ House: $.house, Flat: $.flat }",
            "{ Qlat: $.lat, Qlng: $.lng, info: $$.ToArray()}",
            "$.lat + '|' + $.lng"
        ).ToArray();
    
    console.log(grouped);
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.js"></script>