how to filter multi array list in reactjs

react filter array multiple values
react js filter array of objects
reactjs filter list of objects
javascript filter array of objects by multiple properties
javascript array.filter multiple arguments
javascript filter array multiple values
filter multidimensional array javascript
react table multi select filter

I have tried to implement a search functionality from a list that has multi-array. So I want to search the particular keyword from the array. I have tried but it throws an error.

Array to search from:

const listComponent = [{
    id: 0,
    title: "Common",
    subMenu: [{
      image: "",
      secTitle: "",
      subTitle: ""
    }]
  },
  {
    id: 1,
    title: "Compute",
    subMenu: [{
        image: require("../../assets/images/scaling.png"),
        secTitle: "one comp",
        subTitle: ""
      },
      {
        image: require("../../assets/images/ec2.png"),
        secTitle: "two comp",
        subTitle: ""
      },
      {
        image: require("../../assets/images/lambda.png"),
        secTitle: "three comp",
        subTitle: ""
      },
      {
        image: require("../../assets/images/zone.png"),
        secTitle: "four comp",
        subTitle: ""
      }
    ]
  },
  {
    id: 2,
    title: "Second",
    subMenu: [{
      image: "",
      secTitle: "",
      subTitle: ""
    }]
  },
  {
    id: 3,
    title: "Third",
    subMenu: [{
      image: "",
      secTitle: "",
      subTitle: ""
    }]
  },
  {
    id: 4,
    title: "Fourth",
    subMenu: [{
      image: "",
      secTitle: "",
      subTitle: ""
    }]
  }
];

try changing the key for subMenu. Ideally, you should not use an index as a key as the length and the order of subMenu might change. As Keys help React identify which items have changed, are added, or are removed.

trying changing to this.

              ...
              {items.subMenu.map((submenu, i) => (
                  <li
                    key={`${submenu.secTitle}-${i}`}
                  >
                    <img src={submenu.image} alt="" />
                    <div>
                      <p className="secTitle">{submenu.secTitle}</p>
                      <p className="subTitle">{submenu.subTitle}</p>
                    </div>
                  </li>
                ))}
                ...
// For case-insensitive search

const result = [];

listComponent.forEach((component, index)=> {
  const comp = {...component};
  if(Array.isArray(comp.subMenu)) {
   comp.subMenu = comp.subMenu.filter((subMenu)=> {
     return subMenu.secTitle.toLowerCase().includes(value.toLowerCase());
   });

   if( comp.subMenu.length > 0) {
    result.push(comp);
   }
  }
});
// For case-sensitive search

const result = [];

listComponent.forEach((component, index)=> {
  const comp = {...component};
  if(Array.isArray(comp.subMenu)) {
   comp.subMenu = comp.subMenu.filter((subMenu)=> {
     return subMenu.secTitle.includes(value);
   });

   if( comp.subMenu.length > 0) {
    result.push(comp);
   }
  }
});

Creating a Multi-Filter Function to Filter Out Multiple Attributes Using , Creating a Multi-Filter Function to Filter Out Multiple Attributes Using Javascript of a product's attributes and customer's chosen tags to output a filtered list The filter() method creates a new array with all elements that pass  First use filter to filter the components: let filterResult = components.filter(c => c.subMenu.filter(hasRequiredSecTitle).length > 0); And then filter the subMenu collection of filtered components:


instead of

filterResult = components.filter((component, index) => {
  console.log(component.subMenu[index].secTitle);
  return component.subMenu[index].secTitle.toLowerCase().search(value) !== -1;
});

The code should look something like this:

const listComponent = [
{
    id: 0,
    title: "Common",
    subMenu: [
    {
        image: "",
        secTitle: "abc",
        subTitle: ""
    }
    ]
},
{
    id: 1,
    title: "Common",
    subMenu: [
    {
        image: "",
        secTitle: "def",
        subTitle: ""
    }
    ]
}
]

let value = "abc";

let filterResult = listComponent.filter((component) => {
  return component.subMenu.findIndex((sub) => {
    return sub.secTitle === value;
  }) >= 0;
});

console.log(filterResult);

Use Array.filter() to Dynamically Filter an Array - JavaScript, MyComponent should return a div, an h1, and then an unordered list containing li elements for every user whose online status is set to true. Creating a Multi-Filter Function to Filter Out Multiple Attributes Using Javascript. When one filter just isn’t enough. Nate Park. Follow. May 12,


Okay here's the solution

Change your filterComponents method as this

const filterComponents = (e) => {
  let value = e.target.value;
  let components = [ ...this.state.components];
  const filterData = []
  components.map(item => {
    item.subMenu.reduce((acc, cur) => {
      if (cur.secTitle === value) {
        acc.push(cur)
      }
    }, filterData)
  })
  this.setState({ filterResult: filterData });

  };

filterData will have filtered result

Hope it helps

how to filter multi array list in reactjs – React Questions, I have tried to implement a search functionality from a list that has multi array. So I want to search the particular keyword from the array. When building any type of web application, it’s very common that you will need to handle an array of data. In this article, let me show you how to loop through an array of data using React best


To solve your problem you have first find the top-level item with the item that you want:

From Glen K answer:

let aux = listComponent.filter((component) => {
  return component.subMenu.findIndex((sub) => {
    return sub.secTitle === value;
  }) >= 0;
});

Then you filter the subMenu on the filtered list.

aux = aux.map(item => {
  item.subMenu = item.subMenu.filter((component) => {
    return component.secTitle === value;
  })
  return item;
})

Then save it to your state

filterResult = [...aux];

this.setState({ filterResult });

Search filter for multiple object in ReactJS, for multiple object in ReactJS, Creating a Multi-Filter Function to Filter Create react application; Example to render an array; Implement search filter We have also used the list of columns to be consider as a exclueded  Loading remote data and sorting and filtering that data is simple using native JavaScript. Ext JS initially supplied the functionality prior to native array sorting and filtering. However, browsers have now been supporting these functions since IE9.


You are only filtering the Components, so run the filter again on the subMenus to filter the submenus:

let value = event.target.value;
let components = JSON.parse(JSON.stringify(this.state.components));

// This filter only targets the components themselves...
let filterResult = components.filter(
  component =>
    component.subMenu.findIndex(sub =>
      sub.secTitle.toLowerCase().includes(value)
    ) !== -1
);

// ...so, run the filter again, but this time filter the subMenus
for (let i = 0; i < filterResult.length; i++) {
  filterResult[i].subMenu = [ ...filterResult[i].subMenu];
  filterResult[i].subMenu = filterResult[i].subMenu.filter(
      sub =>
        sub.secTitle.toLowerCase().includes(value)           
  );
}

console.log(filterResult);

Other answers provide cleaner solutions, but I feel like you're misunderstanding how the filter function works. So, I simply reuse your filter code on the subMenus -- hopefully this illustrates the concept that you are missing.

The Snippet below WORKS! So, please take a look... (I had to make a few assumptions about the rest of your code).

'use strict';

function require(url){ return url; };

const listComponent = [
  {
  id: 0,
  title: "Common",
  subMenu: [
    {
      image: "",
      secTitle: "",
      subTitle: ""
    }
  ]
  },
  {
  id: 1,
  title: "Compute",
  subMenu: [
    {
      image: require("../../assets/images/scaling.png"),
      secTitle: "one comp",
      subTitle: ""
    },
    {
      image: require("../../assets/images/ec2.png"),
      secTitle: "two comp",
      subTitle: ""
    },
    {
      image: require("../../assets/images/lambda.png"),
      secTitle: "three comp",
      subTitle: ""
    },
    {
      image: require("../../assets/images/zone.png"),
      secTitle: "four comp",
      subTitle: ""
    }
    ]
    },
  {
  id: 2,
  title: "Second",
  subMenu: [
    {
      image: "",
      secTitle: "",
      subTitle: ""
    }
  ]
  },
  {
  id: 3,
  title: "Third",
  subMenu: [
    {
      image: "",
      secTitle: "",
      subTitle: ""
    }
  ]
  },
  {
  id: 4,
  title: "Fourth",
  subMenu: [
    {
      image: "",
      secTitle: "",
      subTitle: ""
    }
    ]
   }
];

function KeyboardArrowUp(props) {
  return <span>up</span>;
}


class AppComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      components: listComponent,
      filterResult: listComponent
    };

    this.filterComponents = this.filterComponents.bind(this);
  }
  
  filterComponents = event => {
    let value = event.target.value;
    let components = JSON.parse(JSON.stringify(this.state.components));

    // This filter only targets the components themselves...
    let filterResult = components.filter(
      component =>
        component.subMenu.findIndex(sub =>
          sub.secTitle.toLowerCase().includes(value)
        ) !== -1
    );

    // ...so, run the filter again, but this time filter the subMenus
    for (let i = 0; i < filterResult.length; i++) {
      filterResult[i].subMenu = [ ...filterResult[i].subMenu];
      filterResult[i].subMenu = filterResult[i].subMenu.filter(
          sub =>
            sub.secTitle.toLowerCase().includes(value)           
      );
    }
      
    console.log(filterResult);

    this.setState({ filterResult });
  };
  
  UNSAFE_componentWillReceiveProps(nextProps) {
    this.setState({
      components: nextProps.components
    });
  }
  
  openCloseComponent(id) {
    console.log(id);
  }
  
  render() {
    return <div><input type="text" onChange={this.filterComponents} /><br/><ul className="listAll">
            {this.state.filterResult.map((items, key) => (
              <li key={key}>
                <div
                  className="compTitle"
                  onClick={() => this.openCloseComponent(items.id)}
                >
                  <p>{items.title}</p>
                  {this.state.isComOpen === items.id && this.state.isOpen ? (
                    <KeyboardArrowDown className="compArrow" />
                  ) : (
                    <KeyboardArrowUp className="compArrow" />
                  )}
                </div>
                <ul
                  className={
                    this.state.isComOpen === items.id && this.state.isOpen
                      ? "displayBlock secondDrop"
                      : "displayNone"
                  }
                >
                  {items.subMenu.map((submenu, i) => (
                    <li
                      key={i}
                    >
                      <img src={submenu.image} alt="" />
                      <div>
                        <p className="secTitle">{submenu.secTitle}</p>
                        <p className="subTitle">{submenu.subTitle}</p>
                      </div>
                    </li>
                  ))}
                </ul>
              </li>
            ))}
          </ul></div>
          {this.state.filterResult.length === 0 && (
            <p className="noComp">No components found</p>
          )};
  }
}

const domContainer = document.querySelector('#app');
ReactDOM.render(<AppComponent />, domContainer);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app">
  
</div>

Array.filter() Is Awesome, The data from the list was stored in state with an array. I learned multiple ways to manipulate arrays in my studies. You have .pop(), .unshift(),  Render an Array in ReactJS 4. Implement search filter. To implement search filter, we will create one function where we pass the search text and based on it we will filter the records and set it back to the state variable. We have also used the list of columns to be consider as a exclueded columns excludeColumns that we can ignore it from the


React Filter: Filtering Arrays in React (With Examples), This first example is quite a common scenario. Picture the scene: you're creating a search filter component to allow your users to search a list of  var newArray = array.filter(function(item) { return condition; }); The item argument is a reference to the current element in the array as filter() checks it against the condition. This is useful for accessing properties, in the case of objects. If the current item passes the condition, it gets sent to the new array. Filtering an array of objects


Filters an array of objects with multiple match-criteria. · GitHub, `function filterArray<TInput = any>(array: TInput[], filters: IFilters) => TInput[]` Can someone help me change the function multi filter so I can cater for price range instead of just includes? There is also example with React hooks. filteredList = filterPlainArray(array, filterData); console.log(filteredList); // Getting empty List. Multiple Values(Dropdown): Displays the values of the filter in a drop-down list where multiple values can be selected. Multiple Values (Custom List): Displays a text box where you can type a few characters and search for the value. Alternatively, you can type or paste a list of values into the text box to create a custom list of values to include.


filter() Array Method in JavaScript ← Alligator.io, Use filter() on arrays to go through an array and return a new array with the elements that pass the filtering rules. Get 3 http mobile template and reactjs plugins, code & scripts. All from our global community of web developers.