How to filter the entire array based on user input using filter in JavaScript ?

javascript array.filter multiple arguments
javascript filter array multiple values
javascript filter array of objects by another array of objects
filter inside filter javascript
javascript filter object
filter multidimensional array javascript
javascript array filter string contains
javascript filter array of objects by key

I am trying to use a filter in javascript to search on an array. Following is my array:-

 "customerStatusInfoList": [
            {
                "customerId": 1110000012,
                "caseStatus": "pending",
                "customerName": "Robert",
                "dateOfRequest": "2018-12-15 00:00:00.0"
            },
            {
                "customerId": 1110000004,
                "auditorName": "DcbAdmin",
                "caseStatus": "pending",
                "customerName": "Sam",
                "dateOfRequest": "2018-12-14 12:40:04.0"
            }
        ]

And I am using the following function to filter the array:-

  filterTable = event => {
    console.log("event.target.value", event.target.value);
    console.log("rows", this.state.rows);

    if (event.target.value !== "") {
      let newRow = this.state.rows.filter(items => {
        console.log("item.name", items.customerName);
        if (items.customerName!== null)
          return items.customerName
            .toLowerCase()
            .includes(event.target.value.toLowerCase());
      });

      this.setState({ rows: newRow, query: event.target.value });
    } else {
      console.log("Query string is empty ", event.target.value);
      let newRow = this.state.custList;
      console.log("new row :", newRow);
      this.setState({ query: event.target.value, rows: newRow });
    }
  };

I am able to filter on the customerName but when I try to filter using customerId or any other parameter I get customerId.includes is not a function. But it works on customerName. How can I filter on the entire table using JavaScript filter? Any help or suggestion is appreciated. Thank you.

customerId is an integer - you need to cast to string, e.g.:

return `${items.customerId}`
  .toLowerCase()
  .includes(event.target.value.toLowerCase());

btw, items is a confusing name for the variable - it's a single item

also, you can simplify things a bit by decomposing the item, i.e.:

let newRow = this.state.rows.filter(({customerId, customerName}) => 
  `${customerName || ''}`
    .toLowerCase()
    .includes(event.target.value.toLowerCase())
);

to include any row that matches customerId, customerName, or auditorName:

let newRow = this.state.rows.filter(({customerId, customerName, auditorName}) => 
  [customerId, customerName, auditorName].some(field => 
    `${field || ''}`
      .toLowerCase()
      .includes(event.target.value.toLowerCase()))
);

JavaScript Array Filter: Filtering Array Elements Based on a Test , This tutorial shows you how to use the JavaScript array filter method to filter elements in an array based on a specified condition. JavaScript Array filter () method in detail The following illustrates the syntax of the filter () method: arrayObject.filter (callback, contextObject); The filter () method creates a new array with all the elements that pass the test implemented by the callback () function.

I added a test for type in here.

  filterTable = event => {
    console.log("event.target.value", event.target.value);
    console.log("rows", this.state.rows);

    if (event.target.value) {
      let newRow = this.state.rows.filter(items => {
        console.log("item.name", items.customerName);
        if(typeof event.target.value == 'string') {
        if (items.customerName!== null)
              return items.customerName
                          .toLowerCase()
                          .includes(event.target.value.toLowerCase()); 
            } else if(typeof event.target.value === 'number' {
              return items.cusomterId === event.target.value);
            }         
      });

      this.setState({ rows: newRow, query: event.target.value });
    } else {
      console.log("Query string is empty ", event.target.value);
      let newRow = this.state.custList;
      console.log("new row :", newRow);
      this.setState({ query: event.target.value, rows: newRow });
    }
  };

JavaScript Array filter() Method, javascript filter array of objects by key javascript array filter string contains. I am trying to use a filter in javascript to search on an array. Following is my array:- As filter () is a method you call it on the array directly. In the parentheses you need to provide a function which is called once for each item in the array. The argument that is in the function’s parentheses (item in the example above) represents an individual value in the array. The function needs to return either true or false.

Hi I have added some pure javascipt logic which you can embed in your react component as per your need .

Here you can replace the targetName and targetValue comming from the state values of the component.

Having switch case will allow you to add different logic for different kind of fields.

const data = {
    "customerStatusInfoList": [
        {
            "customerId": 1110000012,
            "caseStatus": "pending",
            "customerName": "Robert",
            "dateOfRequest": "2018-12-15 00:00:00.0"
        },
        {
            "customerId": 1110000004,
            "auditorName": "DcbAdmin",
            "caseStatus": "pending",
            "customerName": "Sam",
            "dateOfRequest": "2018-12-14 12:40:04.0"
        }
    ]
}

const targetName = 'customerId';
const targetValue = 1110000004;

callback = (value, index, array) => {

    switch (targetName) {
        case "customerName":
            return value.customerName === targetValue;
        case "customerId":
            return value.customerId === targetValue;
        default:
            return value.customerName === targetValue;
    }
}

let result = data.customerStatusInfoList.filter(callback, this);

JavaScript Filter: Guide on Filtering Arrays and Creating New Ones, The filter() method creates an array filled with all array elements that pass a test Note: filter() does not execute the function for array elements without values. <p​>Minimum age: <input type="number" id="ageToCheck" value="18"></p> reviewed to avoid errors, but we cannot warrant full correctness of all content. Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML. w3schools .com THE WORLD'S LARGEST WEB DEVELOPER SITE

JavaScript, Learn how to use JavaScript filter() to apply a test function on arrays. Therefore, the full syntax of the JavaScript array filter function would look  To do that, we use the filter function. We can perform the filter function inside of our JSX in a React component like so: App.js. <div> { names.filter( name => name.includes('J')).map( filteredName => ( <li> { filteredName } </li> ))} </div>. Let’s break down the code above.

Dynamically filtering an array of objects in JavaScript, The Array.prototype.filter() function is used to create a new array from a given array consisting of only those elements from the Supported Browsers: The browsers supported by JavaScript Array filter() function are listed below: full-​stack-img. I’d like to write a macro which creates a filter using user input in cells with a set of choices from a data validation list. Lets say I have two columns of data — name and age. I’d like to have a separate cell for each variable with a List Data Validation format, and have the user choose how to filter the data via the data validation

Understanding the filter() Method in JavaScript - Joe Cardillo, I recently needed a way to filter an array of objects based on user input. The end-​user This allows for dynamic filtering with n filter criteria. Solved: I want to get a item from array by "Filter" action. How can I use filter for get a item. My scenario: get a link from tweet text.

Comments
  • Because customerId is a number and not a string. consider doing a typeof check and base your test on the type 'string' or 'number'
  • items.customerName you are using customername here you can not filter the customerId
  • It'll throw that error only on customerId since only customerId is a number. Could you a write a simple function to filter and point out what's not working?
  • may be could add toString() before the toLowerCase()
  • thank you but can we stick to filter in javascript rather than using jquery.
  • I'm not using jquery, this is a template string
  • Wow, template strings are awesome. How do I filter multiple items like customerId,customerName, and auditorName using template strings?
  • added that to my answer
  • @PaulThomas is there a better way to filter the entire array using a filter.
  • I think you are using includes because you want partial imput support. ie. "pau" will match "paul thomas". You could convert the number to string also and this would give same functionality across all fields