I'm working on implementing a search filter for my array of objects. Let's assume I have the following array:
let arr = [{'name': 'mn zx abc'}, {'name': 'zx mn'}, {'name': 'mnzx'}]
If I search for zx
, the expected result should be:
[{'name': 'mn zx abc'}, {'name': 'zx mn'}]
However, in the case of the last object {'name': 'mnzx'}
, I want to avoid it as the term zx
is not at the beginning. I hope this clarifies my issue.
Below is the implemented code snippet:
let arr = [{'name': 'mn zx abc'}, {'name': 'zx mn'}, {'name': 'mnzx'}];
let searchedTerm = 'zx';
let result = arr.filter(data => {
if (data.name.charAt(0) === searchedTerm.charAt(0)) {
return true;
}
});
console.log(result);