【问题标题】:Javascript: filter an array of objects into twoJavascript:将对象数组过滤成两个
【发布时间】:2018-10-25 08:56:44
【问题描述】:

我的数组对象如下例所示。

list = [
{'name': 'test1', 'email': 'test1@gmail.com', 'ispin': true, 'updatedAt': 1540456416646}
{'name': 'test2', 'email': 'test2@gmail.com', 'ispin': false, 'updatedAt': 1540456416111}
{'name': 'test3', 'email': 'test3@gmail.com', 'ispin': true, 'updatedAt': 1540456412541}
{'name': 'test4', 'email': 'test4@gmail.com', 'ispin': false, 'updatedAt': 1540456414521}
]

我可以像这样对这个数组对象进行排序。

return conversationList.sort((a, b) => {
  const firstTimestamp = a.lastMessage && a.lastMessage.createdAt ? a.lastMessage.createdAt : 0;
  const secondTimestamp = b.lastMessage && b.lastMessage.createdAt ? b.lastMessage.createdAt : 0;
  //Sort in DESC order
  return secondTimestamp - firstTimestamp;
});

使用上面的代码,我可以按降序对对象数组进行排序。

现在,我的要求是首先基于 ispin 键的过滤器数组。 如果 ispin 设置为 true,那么我想创建新的数组对象,键 pin 也在降序order 和一个数组,键为 recent 以降序排列。

所以我的最终输出应该是这样的。

{ 
  // first array object with key pin : filter by ispin:true and order by descending order
  pin: [
 {'name': 'test1', 'email': 'test1@gmail.com', 'ispin': true, 'updatedAt': 1540456416646}
 {'name': 'test3', 'email': 'test3@gmail.com', 'ispin': true, 'updatedAt': 1540456412541}
 ],
 // second array object with ket recent : order by descending order and records which has ispin false
 recent: [
 {'name': 'test2', 'email': 'test2@gmail.com', 'ispin': false, 'updatedAt': 1540456416111}
 {'name': 'test4', 'email': 'test4@gmail.com', 'ispin': false, 'updatedAt': 1540456414521}
 ]
}

【问题讨论】:

  • 我相信你可以通过.reduce()方法实现这一点。您可以创建一个包含具有isPin:true 的对象的新数组,然后像之前那样对该数组进行排序。
  • @T.J.Crowder :我不认为这个副本是一个好的副本。当您关闭问题时,我正在写一个答案,该问题具有 groupBy 功能(使用 reduce 作为另一条提到的评论)。 OP 在这里需要分组,而不是过滤,这个问题的答案比重复目标要好得多。
  • 啊,对,我认为这毫无意义(并且在查看我的答案时才意识到)。应该是{ pin: [{}] }

标签: javascript arrays sorting filter grouping


【解决方案1】:

要根据 isPin 值拆分您的列表,您可以像这样进行分组:

list = [
  {'name': 'test1', 'email': 'test1@gmail.com', 'ispin': true, 'updatedAt': 1540456416646},
  {'name': 'test2', 'email': 'test2@gmail.com', 'ispin': false, 'updatedAt': 1540456416111},
  {'name': 'test3', 'email': 'test3@gmail.com', 'ispin': true, 'updatedAt': 1540456412541},
  {'name': 'test4', 'email': 'test4@gmail.com', 'ispin': false, 'updatedAt': 1540456414521},
]

const groupBy = (array, fn) => array.reduce((result, item) => {
  const key = fn(item);
  if (!result[key]) result[key] = [];
  result[key].push(item);
  return result;
}, {});

const result = groupBy(list, x => x.ispin ? 'pin' : 'recent');
console.log(result);

(注意:groupBy 灵感来自https://www.reddit.com/r/javascript/comments/4yi7e4/split_an_array_into_2_arrays_based_on_conditions/),正如作者所说,如果你使用这个库,你可以使用来自lodash 的groupBy

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    • 2016-11-12
    • 2012-11-15
    • 2021-10-16
    • 1970-01-01
    相关资源
    最近更新 更多