【问题标题】:Lodash Add Object to already sorted Array of ObejctLodash 将对象添加到已排序的对象数组中
【发布时间】:2017-08-20 00:28:15
【问题描述】:

我正在寻找将一个对象添加到已排序的对象数组中。因此,新数组应该在添加新对象后进行排序。

这是我根据对象属性 displayName 排序的数组

[
  {
    "id": "06BCCC25",
    "displayName":"Application"

  },
  {
    "id": "39F886D9", 
    "displayName":"Communication"
  },
  {
    "id": "22EA4ED5",
     "displayName":"Device"
  },
  {
    "id": "2F6E5FEA",
     "displayName":"Service"
  },
  {
    "id": "317BF72C", "displayName":"Service02"
  }

]

现在我想添加

{
    "id": "07BSSC25",
    "displayName":"Mail"

  }

所以添加后它将被放置在第 3 和第 4 个索引之间。

【问题讨论】:

    标签: javascript arrays node.js object lodash


    【解决方案1】:

    这是我们没有 lodash 的解决方案...

    const records = [{ name: 'a'}, { name: 'b'}, { name: 'c'}, { name: 'd'}];
    const newObjRecord = { name: 'e' };
    
    // inserts into an already sorted array
    // it still works, even if the array is empty
    // it still works, even if the item should be the last
    const inserted = records.some((record, index) => {
        if (record.name > newObjRecord.name) {
            records.splice(index, 0, newObjRecord);
            return true;
        }
        return false;
    });
    // if the array is empty or at the very end, insert it at the end
    if (!inserted) records.push(newObjRecord);
    

    【讨论】:

      【解决方案2】:

      您可以为此使用_.sortedIndexBy(),请参阅:

      例如,您可以使用:

      array.splice(_.sortedIndexBy(array, value, iteratee), 0, value);
      

      其中array 是您的对象数组,value 是要插入的新对象,iteratee 是每个元素调用的函数,它返回您想要对其进行排序的值,但它也可以是属性名称。

      所以在你的情况下,这样的事情应该可以工作:

      array.splice(_.sortedIndexBy(array, value, 'displayName'), 0, value);
      

      只需将您的数组名称替换为array,并将新对象替换为value

      另请参阅 GitHub 上的此问题,其中对此进行了解释:

      如果你经常使用它,你还可以添加一个lodash函数,例如:

      _.insertSorted = (a, v) => a.splice(_.sortedIndex(a, v), 0, v);
      _.insertSortedBy = (a, v, i) => a.splice(_.sortedIndexBy(a, v, i), 0, v);
      

      你可以使用 - 在你的情况下

      _.insertSorted(array, value, 'displayName');
      

      【讨论】:

      • 出于兴趣,这会比将对象推到数组末尾然后对数组进行排序更有效吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 2018-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-01
      • 1970-01-01
      相关资源
      最近更新 更多