Search code examples
javascriptecmascript-6functional-programminglodash

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


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.


Solution

  • 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]));