【问题标题】:How to order array of objects by the number of the keys the same as the given ones as a parameter?如何通过与给定键相同的键数作为参数对对象数组进行排序?
【发布时间】:2018-11-19 16:28:45
【问题描述】:

我有一个带有一些键的基本对象,以及具有相似但不一定完全相同的键的对象列表。

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) {
  // ...
}

结果应该是给定对象的有序数组,基于与基础对象相同的键数。

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

你会用什么?

我正在考虑按对象键上的交集长度进行排序。

【问题讨论】:

  • Object.keys()Array.sort() 和任何形式的循环来检查/计算匹配的属性

标签: javascript ecmascript-6 functional-programming lodash


【解决方案1】:

您可以计算相同的键并将此值用于排序。

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]

【讨论】:

    【解决方案2】:

    您可以使用Object.keysfilter 的组合来确定数组的“真实”长度,并适当地使用sort

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

    【讨论】:

    • 请注意:Array.sort 会变异 arr,这可能是个问题。
    【解决方案3】:

    使用 lodash:

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

    另一种方式:

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

    【讨论】:

    • 我真的很喜欢第一个例子!
    猜你喜欢
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    • 2019-10-08
    • 1970-01-01
    • 2018-04-18
    • 2016-10-20
    • 2018-07-16
    相关资源
    最近更新 更多