skip to Main Content

I want to get the name property value from this array and filter it’s value to a search input data to sort items
how can I do that?

 items: [
            {
                id: 1,
                name: 'Brown Brim',
                imageUrl: 'https://i.ibb.co/ZYW3VTp/brown-brim.png',
                price: 25
            },
            {
                id: 2,
                name: 'Blue Beanie',
                imageUrl: 'https://i.ibb.co/ypkgK0X/blue-beanie.png',
                price: 18
            }

i tried using find() method but it return every object that has a name property

items.find(item => item.name).name.icludes(searchData)

2

Answers


  1. try this

    const newData = items.filter(item => item.name === searchData);
    

    Use newData for your operation.

    Login or Signup to reply.
  2. UPDATED ANSWER

    You said,

    I want to get the name property value from this array and filter it’s value to a search input data to sort items how can I do that?

    Reply me if this isn’t what you want,

    1 => Get an array with only name fields in it.

    items.map(item => item.name);
    `[ 'Brown Brim', 'Blue Beanie' ]`
    

    2 => Then filter the new array according to searchData.

    .filter(item => item.toLowerCase().includes(searchData.toLowercase()));
    

    3 => And sort the filtered array.

    .sort()
    

    4 => finally all together.

    Make sure to assign a variable as newArray because the items array will stay exact the same and our function will return the filtered & sorted array to variable we assign.

      const newArray = items.map(item => item.name)
          .filter(item => item.toLowerCase().includes(searchData.toLowerCase()))
          .sort();
    

    OLD ANSWER

    I’ve modified @sushildlh answer to a more safer version

    const filteredData = items.filter(item => item.name.toLowerCase().includes(searchData.toLowerCase()));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search