Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...