Search code examples
javascriptangularecmascript-6angular6

Typescript - get array that satisfy a condition


Is it possible to get an output array from the given that contains roles=1 without duplicate ? Iam using angular 6 typescript. Is there any typescript array processing functions to do this operation //Input Array

export const userMenus = [
{
    name: 'Dashboard',
    url: '/dashboards',
    icon: 'icon-speedometer',
    roles:'1,3,4'
},
  {
    name: 'Users',
    url: '/Users',
    icon: 'icon-bell',
    roles:'1,2,3,4'
  },
  {
    name: 'Article',
    url: '/Users',
    icon: 'icon-bell',
    roles:'1,2,3,4',
    children: [
             {
              name: 'Cards',
               url: '/base/cards',
               icon: 'icon-puzzle',
               roles:'1,3,4',
             },
             {
               name: 'Carousels',
               url: '/base/carousels',
               icon: 'icon-puzzle',
               roles:'2,4',
             },
             {
               name: 'Collapses',
               url: '/base/collapses',
               icon: 'icon-puzzle',
               roles:'4'
             }
            ]      
  }

]

--Need Output if role is 2. removed items that not contain 2 in the role field

userMenus = [
  {
    name: 'Users',
    url: '/Users',
    icon: 'icon-bell',
    roles:'1,2,3,4'
  },
  {
    name: 'Article',
    url: '/Users',
    icon: 'icon-bell',
    roles:'1,2,3,4',
    children: [
             {
               name: 'Carousels',
               url: '/base/carousels',
               icon: 'icon-puzzle',
               roles:'2,4',
             },
            ]      
  }

Solution

  • You must filter your array and verify that you have 2 in your roles :

    const filteredUserMenus = userMenus.filter((userMenu) => {
      return userMenu.roles.find((role) => role === '2');
    });
    

    short syntax :

    const filteredUserMenus = userMenus.filter((userMenu) => 
      userMenu.roles.find((role) => role === '2'));
    

    EDIT : your data structure is bad, roles shouldn't be a string but an array of role. Anyway, if you can't change it, here is a solution :

    const filteredUserMenus = userMenus.filter((userMenu) => {
      return userMenu.roles.split(',').find((role) => role === '2');
    });
    

    short syntax :

    const filteredUserMenus = userMenus.filter((userMenu) =>
       userMenu.roles.split(',').find((role) => role === '2'));