Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

javascript - use lodash for iterating the array and filter

I have a function called as

getFileterMenus = (menus, filterMenu) => {
    let filteredMenus = _.filter(menus, menu => menu.title !== filterMenu)
    return filteredMenus
  }

Here filterMenu I want to pass it as an array . which will be like ['first', 'second'] like this. I want to keep a filter function as well.. I tried

getFileterMenus = (menus, filterMenu) => {
         let filteredMenus = []
         for (let i = 0; i <= filterMenu.length - 1; i++) {
           filteredMenus = _.filter(menus, menu => menu.title !== filterMenu[i])
          } 
        return filteredMenus
      }

Is there any other way to do this than using a loop ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming that menus is an array of objects and filterMenu contains an array of titles that you want to filter for, you can do it with ES6 completely without using lodash, using a combination of Array.prototype.filter and Array.prototype.includes:

getFileterMenus = (menus, filterMenu) => {
  return menus.filter(menu => !filterMenu.includes(menu.title));
}

If you really want to get creative at the expense of readability, a one-liner with object destructring:

getFileterMenus = (menus, filterMenu) => menus.filter(({ title })=> !filterMenu.includes(title))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...