最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to filter multiple values in React - Stack Overflow

programmeradmin0浏览0评论

I am trying to search an array but in meantime I am able to search on just first name what I want to achieve I want to include last Name too . For example if user search which contain last name or first name I want to display a data . Could someone please help me how to resolve this issue.

Code

 handleByNameChange = (e) => {
    let value = e.target.value;
    let updatedList = this.props.userData.allUsersForFilter;
    updatedList = updatedList.filter(function (item) {
      return item.firstName.toLowerCase().search(value.toLowerCase()) !== -1;
    });

    this.setState({
      byNameInputValue: value,
      items: updatedList,
    });
  };

Array of object

[
{firstName: 'Martin', lastName :'Jonas'},
{firstName:'Brad',lastName:'Mickle'},
{fitstName: 'Summer, lastName:'Bride'}
]

I am trying to search an array but in meantime I am able to search on just first name what I want to achieve I want to include last Name too . For example if user search which contain last name or first name I want to display a data . Could someone please help me how to resolve this issue.

Code

 handleByNameChange = (e) => {
    let value = e.target.value;
    let updatedList = this.props.userData.allUsersForFilter;
    updatedList = updatedList.filter(function (item) {
      return item.firstName.toLowerCase().search(value.toLowerCase()) !== -1;
    });

    this.setState({
      byNameInputValue: value,
      items: updatedList,
    });
  };

Array of object

[
{firstName: 'Martin', lastName :'Jonas'},
{firstName:'Brad',lastName:'Mickle'},
{fitstName: 'Summer, lastName:'Bride'}
]
Share Improve this question asked Jul 14, 2020 at 6:16 Jonas Jonas 2711 gold badge3 silver badges15 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 5

Create a function that takes an array to search, and array of property keys to search by, and a value to search for. If array of property keys is empty then no filter should probably occur, return all elements.

  • Use array:some to return true/false if using one of the property keys conditions is met.
  • Use string::includes to test if a string contains a substring.

searchBy function

const searchBy = (arr = [], searchKeys = [], value = '') => {
  return arr.filter(item =>
    searchKeys.length ? searchKeys.some(key =>
      (item[key] || "").toLowerCase().includes(value.toLowerCase())
    ) : true
  );
};

Usage

handleByNameChange = (e) => {
  const { value } = e.target;
  const updatedList = this.props.userData.allUsersForFilter;

  this.setState({
    byNameInputValue: value,
    items: searchBy(updatedList, ['firstName', 'lastName'], value),
  });
};

const data = [
  { firstName: "Martin", lastName: "Jonas" },
  { firstName: "Brad", lastName: "Mickle" },
  { firstName: "Summer", lastName: "Bride" },
  { firstName: "Axel", lastName: "Rod" },
  { firstName: "Mike", lastName: "Haxel" }
];

const searchBy = (arr = [], searchKeys = [], value = '') => {
  return arr.filter(item =>
    searchKeys.length ? searchKeys.some(key =>
      (item[key] || "").toLowerCase().includes(value.toLowerCase())
    ) : true
  );
};

console.log(searchBy(data, [], "Martin"));
console.log(searchBy(data, ["lastName"], ""));
console.log(searchBy(data, ["firstName"], "Martin"));
console.log(searchBy(data, ["firstName"], "Summer"));
console.log(searchBy(data, ["firstName", "lastName"], "ax"));

Addendum - Searching for bined full name

const searchByName = (arr = [], value = "") => {
  return arr.filter(({ firstName = '', lastName = '' }) =>
    [firstName, lastName, `${firstName} ${lastName}`].some(el =>
      el.toLowerCase().includes(value.toLowerCase())
    )
  );
};

Tries to match first or last name, then full name

const data = [
  { firstName: "Martin", lastName: "Jonas" },
  { firstName: "Brad", lastName: "Mickle" },
  { firstName: "Summer", lastName: "Bride" },
  { firstName: "Axel", lastName: "Rod" },
  { firstName: "Mike", lastName: "Haxel" }
];

const searchByName = (arr = [], value = "") => {
  return arr.filter(({ firstName = '', lastName = '' }) =>
    [firstName, lastName, `${firstName} ${lastName}`].some(el =>
      el.toLowerCase().includes(value.toLowerCase())
    )
  );
};

console.log(searchByName(data, "Martin"));
console.log(searchByName(data, ""));
console.log(searchByName(data, "Summer"));
console.log(searchByName(data, "ax"));
console.log(searchByName(data, "Mike Ha"));

All code in sandbox demo

Use some method on bining firstName and lastName array. (Alternatively return (firstName check || lastName check)

data = [
  { firstName: "Martin", lastName: "Jonas" },
  { firstName: "Brad", lastName: "Mickle" },
  { firstName: "Summer", lastName: "Bride" },
];
value = "ride";
updatedList = data.filter(({ firstName, lastName }) =>
  [firstName, lastName].some(
    (name) => name.toLowerCase().search(value.toLowerCase()) !== -1
  )
);

console.log(updatedList);

Is this you are looking for ?

const data = [
{firstName: 'Martin', lastName :'Jonas'},
{firstName:'Brad',lastName:'Mickle'},
{firstName:'Summer',lastName:'Bride'}
]

//anyName , which might be first Name or last Name

function filterData(anyName){
        const res = data.filter(name => (name.firstName.includes(anyName)||name.lastName.includes(anyName)))
        return res;
}


console.log(filterData('ride'))

You can do something like this:

const updatedList = [
  {firstName: 'Martin', lastName :'Jonas'},
  {firstName:'Brad',lastName:'Mickle'},
  {firstName: 'Summer', lastName:'Bride'}
  ];

  updatedList = updatedList.filter(function (item) {
    return item.firstName.toLowerCase().search(value.toLowerCase()) !== -1 || 
     item.lastName.toLowerCase().search(value.toLowerCase()) !== -1;
  });
updatedList = updatedList.filter(function (item) {
    if(value) {
        return item.firstName.toLowerCase().indexOf(value.toLowerCase()) > -1 || item.lastName.toLowerCase().indexOf(value.toLowerCase()) > -1;
      } else {
      return "";
      }
});

This is a very basic checking which is clear and concise one, it checks whether the first name or last name values have matched items with provided items or not.

发布评论

评论列表(0)

  1. 暂无评论