0

I have a simple array, I want to make a search functionality on this array. I have an input where I enter data to search. But the search goes through all the lines of the object, and I need only lines name and day.

How can the code below be modified to implement this functionality, do you have a better option for this?

const data =[
 {
  name: 'name',
  day: 'monday',
  year: '2023',
  user:'user13421'
 },
 {
  name: 'name1',
  day: 'monday1',
  year: '20231',
  user:'user134211'
 }
]


let filtered;
  const onSearchF = (keyword) => {
    filtered = data.filter((entry) =>
      Object.values(entry).some(
        (val) =>
          typeof val === "string" &&
          val.toLowerCase().includes(keyword.toLowerCase())
      )
    );
  };
wch
  • 276
  • 4
  • 16
  • Than do not loop all the entry values, check only `entry.name` and `entry.day`. – skobaljic Mar 02 '23 at 10:41
  • Does this answer your question? [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – traynor Mar 02 '23 at 10:42

2 Answers2

2
const data =[
 {
  name: 'name',
  day: 'monday',
  year: '2023',
  user:'user13421'
 },
 {
  name: 'name1',
  day: 'monday1',
  year: '20231',
  user:'user134211'
 }
]


const filterKeys = ['name', 'day'];
let filtered;

  const onSearchF = (keyword) => {
    const lowerKeyword = keyword.toLowerCase();
    filtered = data.filter((entry) => {
        return filterKeys.some(key => entry[key].toLowerCase().includes(lowerKeyword));
    });
  };

I would advise, if possible, instead of modifying external variable, to return filtered array, like this:

const data =[
 {
  name: 'name',
  day: 'monday',
  year: '2023',
  user:'user13421'
 },
 {
  name: 'name1',
  day: 'monday1',
  year: '20231',
  user:'user134211'
 }
]


const filterKeys = ['name', 'day'];

  const onSearchF = (keyword) => {
    const lowerKeyword = keyword.toLowerCase();
    return data.filter((entry) => {
        return filterKeys.some(key => entry[key].toLowerCase().includes(lowerKeyword));
    });
  };
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Artem
  • 56
  • 5
1

You can just search the two properties only. This works:

const onSearchF = (keyword) => {
    filtered = data.filter((entry) => (
        entry.day.toLowerCase().includes(keyword.toLowerCase()) ||
        entry.name.toLowerCase().includes(keyword.toLowerCase())
    ));
};

If you want to be fancier and not repeat those two lines of code you can do this:

let filtered;
const onSearchF = (keyword) => {
    filtered = data.filter((entry) => (
        [entry.day, entry.name].some(val => val.toLowerCase().includes(keyword.toLowerCase()) )
    ));
};

but I'm not sure it's better tho

Odilf
  • 1,185
  • 7
  • 12