How to order array of objects by the number of the keys the same as the given ones as a parameter?












1















I have a basic object with some keys, and the list of objects with similar, but not necessarily the exact same, keys.



const o1 = {k1: "", k2: "", k3: ""} // the basic object
const o2 = {k1: "", k4: ""} // 1 the same key
const o3 = {k1: "", k3: ""} // 2 the same keys
const o4 = {k3: "", k1: "", k2: ""} // 3 the same keys
const o5 = {k5: ""} // 0 the same keys


I want to write a function which takes the base object and an array of other objects, and it will sort/order them by the number of similar keys in the given object.



function order(obj, arr) {
// ...
}


The result should be the ordered array of the given objects based on the number of the same keys as the base object.



order(o1, [o2, o3, o4, o5])
// result: [o4, o3, o2, o5]


What would you use for that?



I was thinking about sorting by the length of intersection on objects keys.










share|improve this question

























  • Object.keys(), Array.sort() and any form of loop to check/count the matching properties

    – Andreas
    Nov 19 '18 at 16:31
















1















I have a basic object with some keys, and the list of objects with similar, but not necessarily the exact same, keys.



const o1 = {k1: "", k2: "", k3: ""} // the basic object
const o2 = {k1: "", k4: ""} // 1 the same key
const o3 = {k1: "", k3: ""} // 2 the same keys
const o4 = {k3: "", k1: "", k2: ""} // 3 the same keys
const o5 = {k5: ""} // 0 the same keys


I want to write a function which takes the base object and an array of other objects, and it will sort/order them by the number of similar keys in the given object.



function order(obj, arr) {
// ...
}


The result should be the ordered array of the given objects based on the number of the same keys as the base object.



order(o1, [o2, o3, o4, o5])
// result: [o4, o3, o2, o5]


What would you use for that?



I was thinking about sorting by the length of intersection on objects keys.










share|improve this question

























  • Object.keys(), Array.sort() and any form of loop to check/count the matching properties

    – Andreas
    Nov 19 '18 at 16:31














1












1








1








I have a basic object with some keys, and the list of objects with similar, but not necessarily the exact same, keys.



const o1 = {k1: "", k2: "", k3: ""} // the basic object
const o2 = {k1: "", k4: ""} // 1 the same key
const o3 = {k1: "", k3: ""} // 2 the same keys
const o4 = {k3: "", k1: "", k2: ""} // 3 the same keys
const o5 = {k5: ""} // 0 the same keys


I want to write a function which takes the base object and an array of other objects, and it will sort/order them by the number of similar keys in the given object.



function order(obj, arr) {
// ...
}


The result should be the ordered array of the given objects based on the number of the same keys as the base object.



order(o1, [o2, o3, o4, o5])
// result: [o4, o3, o2, o5]


What would you use for that?



I was thinking about sorting by the length of intersection on objects keys.










share|improve this question
















I have a basic object with some keys, and the list of objects with similar, but not necessarily the exact same, keys.



const o1 = {k1: "", k2: "", k3: ""} // the basic object
const o2 = {k1: "", k4: ""} // 1 the same key
const o3 = {k1: "", k3: ""} // 2 the same keys
const o4 = {k3: "", k1: "", k2: ""} // 3 the same keys
const o5 = {k5: ""} // 0 the same keys


I want to write a function which takes the base object and an array of other objects, and it will sort/order them by the number of similar keys in the given object.



function order(obj, arr) {
// ...
}


The result should be the ordered array of the given objects based on the number of the same keys as the base object.



order(o1, [o2, o3, o4, o5])
// result: [o4, o3, o2, o5]


What would you use for that?



I was thinking about sorting by the length of intersection on objects keys.







javascript ecmascript-6 functional-programming lodash






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 19 '18 at 16:39







Kamil Lelonek

















asked Nov 19 '18 at 16:28









Kamil LelonekKamil Lelonek

9,45594876




9,45594876













  • Object.keys(), Array.sort() and any form of loop to check/count the matching properties

    – Andreas
    Nov 19 '18 at 16:31



















  • Object.keys(), Array.sort() and any form of loop to check/count the matching properties

    – Andreas
    Nov 19 '18 at 16:31

















Object.keys(), Array.sort() and any form of loop to check/count the matching properties

– Andreas
Nov 19 '18 at 16:31





Object.keys(), Array.sort() and any form of loop to check/count the matching properties

– Andreas
Nov 19 '18 at 16:31












3 Answers
3






active

oldest

votes


















1














You can use a combination of Object.keys and filter to determine the "real" length of the array and sort appropriately:






const o1 = {k1: "", k2: "", k3: ""} // the basic object
const o2 = {k1: "", k4: ""} // 1 the same key
const o3 = {k1: "", k3: ""} // 2 the same keys
const o4 = {k3: "", k1: "", k2: ""} // 3 the same keys
const o5 = {k5: ""} // 0 the same keys

function order(obj, arr) {
return arr.sort((a, b) =>
Object.keys(b).filter(k => k in obj).length -
Object.keys(a).filter(k => k in obj).length);
}

console.log(order(o1, [o2, o3, o4, o5]));








share|improve this answer
























  • Just a caveat: Array.sort will mutate arr, which may be a problem.

    – tokland
    Nov 19 '18 at 22:36



















2














You could count same keys and take this value for sorting.






const
o1 = { k1: "", k2: "", k3: "" }, // the basic object
o2 = { k1: "", k4: "" }, // 1 the same key
o3 = { k1: "", k3: "" }, // 2 the same keys
o4 = { k3: "", k1: "", k2: "" }, // 3 the same keys
o5 = { k5: "" }; // 0 the same keys

function order(object, array) {
function getCount(o) {
return Object.keys(object).reduce((s, k) => s + (k in o), 0);
}
return array.sort((a, b) => getCount(b) - getCount(a));
}

console.log(order(o1, [o2, o3, o4, o5])); // [o4, o3, o2, o5]








share|improve this answer































    1














    Using lodash:



    function order(reference, objs) {
    const referenceKeys = _.keys(reference);
    return _.sortBy(objs, obj => -_(referenceKeys).intersection(_.keys(obj)).size());
    }


    Another way:



    function order(reference, objs) {
    const referenceKeys = new Set(_.keys(reference));
    return _.sortBy(objs, obj => _(obj).keys().sumBy(key => referenceKeys.has(key) ? -1 : 0))
    }





    share|improve this answer


























    • I really like the first example!

      – Kamil Lelonek
      Nov 19 '18 at 23:45











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53378929%2fhow-to-order-array-of-objects-by-the-number-of-the-keys-the-same-as-the-given-on%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    You can use a combination of Object.keys and filter to determine the "real" length of the array and sort appropriately:






    const o1 = {k1: "", k2: "", k3: ""} // the basic object
    const o2 = {k1: "", k4: ""} // 1 the same key
    const o3 = {k1: "", k3: ""} // 2 the same keys
    const o4 = {k3: "", k1: "", k2: ""} // 3 the same keys
    const o5 = {k5: ""} // 0 the same keys

    function order(obj, arr) {
    return arr.sort((a, b) =>
    Object.keys(b).filter(k => k in obj).length -
    Object.keys(a).filter(k => k in obj).length);
    }

    console.log(order(o1, [o2, o3, o4, o5]));








    share|improve this answer
























    • Just a caveat: Array.sort will mutate arr, which may be a problem.

      – tokland
      Nov 19 '18 at 22:36
















    1














    You can use a combination of Object.keys and filter to determine the "real" length of the array and sort appropriately:






    const o1 = {k1: "", k2: "", k3: ""} // the basic object
    const o2 = {k1: "", k4: ""} // 1 the same key
    const o3 = {k1: "", k3: ""} // 2 the same keys
    const o4 = {k3: "", k1: "", k2: ""} // 3 the same keys
    const o5 = {k5: ""} // 0 the same keys

    function order(obj, arr) {
    return arr.sort((a, b) =>
    Object.keys(b).filter(k => k in obj).length -
    Object.keys(a).filter(k => k in obj).length);
    }

    console.log(order(o1, [o2, o3, o4, o5]));








    share|improve this answer
























    • Just a caveat: Array.sort will mutate arr, which may be a problem.

      – tokland
      Nov 19 '18 at 22:36














    1












    1








    1







    You can use a combination of Object.keys and filter to determine the "real" length of the array and sort appropriately:






    const o1 = {k1: "", k2: "", k3: ""} // the basic object
    const o2 = {k1: "", k4: ""} // 1 the same key
    const o3 = {k1: "", k3: ""} // 2 the same keys
    const o4 = {k3: "", k1: "", k2: ""} // 3 the same keys
    const o5 = {k5: ""} // 0 the same keys

    function order(obj, arr) {
    return arr.sort((a, b) =>
    Object.keys(b).filter(k => k in obj).length -
    Object.keys(a).filter(k => k in obj).length);
    }

    console.log(order(o1, [o2, o3, o4, o5]));








    share|improve this answer













    You can use a combination of Object.keys and filter to determine the "real" length of the array and sort appropriately:






    const o1 = {k1: "", k2: "", k3: ""} // the basic object
    const o2 = {k1: "", k4: ""} // 1 the same key
    const o3 = {k1: "", k3: ""} // 2 the same keys
    const o4 = {k3: "", k1: "", k2: ""} // 3 the same keys
    const o5 = {k5: ""} // 0 the same keys

    function order(obj, arr) {
    return arr.sort((a, b) =>
    Object.keys(b).filter(k => k in obj).length -
    Object.keys(a).filter(k => k in obj).length);
    }

    console.log(order(o1, [o2, o3, o4, o5]));








    const o1 = {k1: "", k2: "", k3: ""} // the basic object
    const o2 = {k1: "", k4: ""} // 1 the same key
    const o3 = {k1: "", k3: ""} // 2 the same keys
    const o4 = {k3: "", k1: "", k2: ""} // 3 the same keys
    const o5 = {k5: ""} // 0 the same keys

    function order(obj, arr) {
    return arr.sort((a, b) =>
    Object.keys(b).filter(k => k in obj).length -
    Object.keys(a).filter(k => k in obj).length);
    }

    console.log(order(o1, [o2, o3, o4, o5]));





    const o1 = {k1: "", k2: "", k3: ""} // the basic object
    const o2 = {k1: "", k4: ""} // 1 the same key
    const o3 = {k1: "", k3: ""} // 2 the same keys
    const o4 = {k3: "", k1: "", k2: ""} // 3 the same keys
    const o5 = {k5: ""} // 0 the same keys

    function order(obj, arr) {
    return arr.sort((a, b) =>
    Object.keys(b).filter(k => k in obj).length -
    Object.keys(a).filter(k => k in obj).length);
    }

    console.log(order(o1, [o2, o3, o4, o5]));






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 19 '18 at 16:36









    sliderslider

    8,16511129




    8,16511129













    • Just a caveat: Array.sort will mutate arr, which may be a problem.

      – tokland
      Nov 19 '18 at 22:36



















    • Just a caveat: Array.sort will mutate arr, which may be a problem.

      – tokland
      Nov 19 '18 at 22:36

















    Just a caveat: Array.sort will mutate arr, which may be a problem.

    – tokland
    Nov 19 '18 at 22:36





    Just a caveat: Array.sort will mutate arr, which may be a problem.

    – tokland
    Nov 19 '18 at 22:36













    2














    You could count same keys and take this value for sorting.






    const
    o1 = { k1: "", k2: "", k3: "" }, // the basic object
    o2 = { k1: "", k4: "" }, // 1 the same key
    o3 = { k1: "", k3: "" }, // 2 the same keys
    o4 = { k3: "", k1: "", k2: "" }, // 3 the same keys
    o5 = { k5: "" }; // 0 the same keys

    function order(object, array) {
    function getCount(o) {
    return Object.keys(object).reduce((s, k) => s + (k in o), 0);
    }
    return array.sort((a, b) => getCount(b) - getCount(a));
    }

    console.log(order(o1, [o2, o3, o4, o5])); // [o4, o3, o2, o5]








    share|improve this answer




























      2














      You could count same keys and take this value for sorting.






      const
      o1 = { k1: "", k2: "", k3: "" }, // the basic object
      o2 = { k1: "", k4: "" }, // 1 the same key
      o3 = { k1: "", k3: "" }, // 2 the same keys
      o4 = { k3: "", k1: "", k2: "" }, // 3 the same keys
      o5 = { k5: "" }; // 0 the same keys

      function order(object, array) {
      function getCount(o) {
      return Object.keys(object).reduce((s, k) => s + (k in o), 0);
      }
      return array.sort((a, b) => getCount(b) - getCount(a));
      }

      console.log(order(o1, [o2, o3, o4, o5])); // [o4, o3, o2, o5]








      share|improve this answer


























        2












        2








        2







        You could count same keys and take this value for sorting.






        const
        o1 = { k1: "", k2: "", k3: "" }, // the basic object
        o2 = { k1: "", k4: "" }, // 1 the same key
        o3 = { k1: "", k3: "" }, // 2 the same keys
        o4 = { k3: "", k1: "", k2: "" }, // 3 the same keys
        o5 = { k5: "" }; // 0 the same keys

        function order(object, array) {
        function getCount(o) {
        return Object.keys(object).reduce((s, k) => s + (k in o), 0);
        }
        return array.sort((a, b) => getCount(b) - getCount(a));
        }

        console.log(order(o1, [o2, o3, o4, o5])); // [o4, o3, o2, o5]








        share|improve this answer













        You could count same keys and take this value for sorting.






        const
        o1 = { k1: "", k2: "", k3: "" }, // the basic object
        o2 = { k1: "", k4: "" }, // 1 the same key
        o3 = { k1: "", k3: "" }, // 2 the same keys
        o4 = { k3: "", k1: "", k2: "" }, // 3 the same keys
        o5 = { k5: "" }; // 0 the same keys

        function order(object, array) {
        function getCount(o) {
        return Object.keys(object).reduce((s, k) => s + (k in o), 0);
        }
        return array.sort((a, b) => getCount(b) - getCount(a));
        }

        console.log(order(o1, [o2, o3, o4, o5])); // [o4, o3, o2, o5]








        const
        o1 = { k1: "", k2: "", k3: "" }, // the basic object
        o2 = { k1: "", k4: "" }, // 1 the same key
        o3 = { k1: "", k3: "" }, // 2 the same keys
        o4 = { k3: "", k1: "", k2: "" }, // 3 the same keys
        o5 = { k5: "" }; // 0 the same keys

        function order(object, array) {
        function getCount(o) {
        return Object.keys(object).reduce((s, k) => s + (k in o), 0);
        }
        return array.sort((a, b) => getCount(b) - getCount(a));
        }

        console.log(order(o1, [o2, o3, o4, o5])); // [o4, o3, o2, o5]





        const
        o1 = { k1: "", k2: "", k3: "" }, // the basic object
        o2 = { k1: "", k4: "" }, // 1 the same key
        o3 = { k1: "", k3: "" }, // 2 the same keys
        o4 = { k3: "", k1: "", k2: "" }, // 3 the same keys
        o5 = { k5: "" }; // 0 the same keys

        function order(object, array) {
        function getCount(o) {
        return Object.keys(object).reduce((s, k) => s + (k in o), 0);
        }
        return array.sort((a, b) => getCount(b) - getCount(a));
        }

        console.log(order(o1, [o2, o3, o4, o5])); // [o4, o3, o2, o5]






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 19 '18 at 16:41









        Nina ScholzNina Scholz

        178k1491157




        178k1491157























            1














            Using lodash:



            function order(reference, objs) {
            const referenceKeys = _.keys(reference);
            return _.sortBy(objs, obj => -_(referenceKeys).intersection(_.keys(obj)).size());
            }


            Another way:



            function order(reference, objs) {
            const referenceKeys = new Set(_.keys(reference));
            return _.sortBy(objs, obj => _(obj).keys().sumBy(key => referenceKeys.has(key) ? -1 : 0))
            }





            share|improve this answer


























            • I really like the first example!

              – Kamil Lelonek
              Nov 19 '18 at 23:45
















            1














            Using lodash:



            function order(reference, objs) {
            const referenceKeys = _.keys(reference);
            return _.sortBy(objs, obj => -_(referenceKeys).intersection(_.keys(obj)).size());
            }


            Another way:



            function order(reference, objs) {
            const referenceKeys = new Set(_.keys(reference));
            return _.sortBy(objs, obj => _(obj).keys().sumBy(key => referenceKeys.has(key) ? -1 : 0))
            }





            share|improve this answer


























            • I really like the first example!

              – Kamil Lelonek
              Nov 19 '18 at 23:45














            1












            1








            1







            Using lodash:



            function order(reference, objs) {
            const referenceKeys = _.keys(reference);
            return _.sortBy(objs, obj => -_(referenceKeys).intersection(_.keys(obj)).size());
            }


            Another way:



            function order(reference, objs) {
            const referenceKeys = new Set(_.keys(reference));
            return _.sortBy(objs, obj => _(obj).keys().sumBy(key => referenceKeys.has(key) ? -1 : 0))
            }





            share|improve this answer















            Using lodash:



            function order(reference, objs) {
            const referenceKeys = _.keys(reference);
            return _.sortBy(objs, obj => -_(referenceKeys).intersection(_.keys(obj)).size());
            }


            Another way:



            function order(reference, objs) {
            const referenceKeys = new Set(_.keys(reference));
            return _.sortBy(objs, obj => _(obj).keys().sumBy(key => referenceKeys.has(key) ? -1 : 0))
            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 19 '18 at 22:46

























            answered Nov 19 '18 at 22:12









            toklandtokland

            51.7k11115143




            51.7k11115143













            • I really like the first example!

              – Kamil Lelonek
              Nov 19 '18 at 23:45



















            • I really like the first example!

              – Kamil Lelonek
              Nov 19 '18 at 23:45

















            I really like the first example!

            – Kamil Lelonek
            Nov 19 '18 at 23:45





            I really like the first example!

            – Kamil Lelonek
            Nov 19 '18 at 23:45


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53378929%2fhow-to-order-array-of-objects-by-the-number-of-the-keys-the-same-as-the-given-on%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            MongoDB - Not Authorized To Execute Command

            Npm cannot find a required file even through it is in the searched directory

            in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith