0

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.

4
  • Because customerId is a number and not a string. consider doing a typeof check and base your test on the type 'string' or 'number' Commented Dec 18, 2018 at 4:15
  • 1
    items.customerName you are using customername here you can not filter the customerId Commented Dec 18, 2018 at 4:15
  • 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? Commented Dec 18, 2018 at 4:21
  • may be could add toString() before the toLowerCase() Commented Dec 18, 2018 at 4:32

3 Answers 3

1

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()))
);
Sign up to request clarification or add additional context in comments.

4 Comments

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
1

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

2 Comments

@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
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.