【问题标题】:how to find a filtered array in lodash?如何在 lodash 中找到过滤后的数组?
【发布时间】:2018-02-06 09:25:26
【问题描述】:

我正在研究 lodash,我需要从数组的大集合中过滤数据。数组的集合就是这种类型的数据:

[ { poll_options: [ [Object] ],
    responder_ids: [ '5a7189c14615db31ecd54347', '59ffb41f62d346204e0a199b' ],
    voted_ids: [ '5a7189c14615db31ecd54347' ],
    _id: 5a7878833a1bf4238ddc5cef },
  { poll_options: [ [Object] ],
    responder_ids: [ '5a7189c14615db31ecd54347' ],
    voted_ids: [ '5a7189c14615db31ecd54347' ],
    _id: 5a787756217db51698ea8fd6 } ]

我想过滤其中包含不在 voted_ids 中的 ids 值的数组(即对于第一个对象,它应该返回这个 59ffb41f62d346204e0a199b nd 对于第二个集合,它应该返回空数组)这意味着我必须只返回那些不在 voted_ids 上但在 responder_ids 上的值。我的代码是这样的

_.map(polls,(poll) => {
                        // console.log(poll.responder_ids)
                        return _.filter(poll.responder_ids,(responder) => {
                          return _.find(poll.voted_ids,(voted) => {
                            return !_.includes(responder,voted)
                          })

但它不返回过滤后的数组,而是返回整个集合。我做错了什么??

现在它的返回结果是这样的......

[ [ '59ffb41f62d346204e0a199b' ], [] ]

我想要单个数组而不是多数组。

【问题讨论】:

  • _.filter 总是返回一个真实的值,你可能想要 _.some 代替。
  • 而不是_.map 使用_.flatMap

标签: javascript arrays lodash


【解决方案1】:

您以错误的方式使用_.filter

过滤器遍历数组中的所有项目。如果过滤函数返回true,则该项目将在过滤后的数组中返回,如果返回false,则不会返回。

但是,您正在返回一个数组,结果为truthy,因此所有项目都被返回。

你想要的是这样的:

const polls = [
  { 
    poll_options: [ '[Object]' ],
    responder_ids: [ '5a7189c14615db31ecd54347', '59ffb41f62d346204e0a199b' ],
    voted_ids: [ '5a7189c14615db31ecd54347' ],
    _id: '5a7878833a1bf4238ddc5cef'
  },
  { 
    poll_options: [ '[Object]' ],
    responder_ids: [ '5a7189c14615db31ecd54347' ],
    voted_ids: [ '5a7189c14615db31ecd54347' ],
    _id: '5a787756217db51698ea8fd6'
  }
];

let ids = [];
for (let i = 0; i < polls.length; i++) {
  ids = [...ids, ...polls[i].responder_ids.filter(id => {
    return !polls[i].voted_ids.includes(id);
  })];
}
console.log(ids);

【讨论】:

  • 我应该用什么来代替过滤器??
  • 谢谢 :-)
【解决方案2】:

这不是使用filter 函数的正确方法。在回调函数中,您应该返回一些 boolean 值,以便可以按该标准过滤数组。 如果我对您的理解正确,您希望通过数组进行过滤以获取当 id 在responder_ids 中但不在voted_ids 中时包含所有结果的数组。它可以通过多种方式解决,即:

_.filter(polls, poll => _.findIndex(poll.responder_ids, id => id === '59ffb41f62d346204e0a199b') > -1 && _.findIndex(poll.voted_ids, id => id === '59ffb41f62d346204e0a199b') === -1;
    );

【讨论】:

    猜你喜欢
    • 2017-05-05
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    • 2012-10-09
    • 2016-03-30
    • 2019-10-17
    • 1970-01-01
    • 2018-02-27
    相关资源
    最近更新 更多