skip to Main Content

I have an array of array and I want to show only array with the substring from a search bar.

My code :

In the first part (not show) I get value from search bar and had a space before (to see all arrays if nothing is write)

 const Arrays = [
 [
  { text: " first ", image: "1.jpg", },
  " hello"," world"," ",
],
[
  {text: " second",image: "https://www.wikipedia.org/portal/wikipedia.org/assets/img/Wikipedia-logo-v2.png",},
  " goodbye"," world"," ",
],
[
  { text: " Salut", image: "bass.jpg", },
  " Ca va"," au revoir"," ",
],
];

const showArrays = Arrays.filter(function(array) {return array.includes(searchimp) })

That is my filter fonction, it work only if searchimp was exactly same with an element from an subarray

With searchimp my const from search bar.

At end I have a function (not show) to show "showArrays" and format each first element from each array to show pictures and there alt

It run, when I write "goodbye" it return the second array but when I write "goo" it did’nt return anything.

2

Answers


  1. To search for a substring, you can use the indexOf method.

    To bypass a nested array, it is better to use the some method

    const Arrays = [
      [
        { text: " first ", image: "1.jpg", },
        " hello"," world"," ",
      ],
      [
        {text: " second",image: "https://www.wikipedia.org/portal/wikipedia.org/assets/img/Wikipedia-logo-v2.png",},
        " goodbye"," world"," ",
      ],
      [
        { text: " Salut", image: "bass.jpg", },
        " Ca va"," au revoir"," ",
      ],
    ];
    const searchimp = prompt('What find? ')
    const showArrays = Arrays.filter(function (array) {
      return array.some(el => { // iterate
        if (typeof el === 'string') { // search in string
          return el.indexOf(searchimp) > -1; // if find, return true and stop iterate
        }
        return false;
      })
    })
    
    console.log(showArrays);

    One line record

    const showArrays = Arrays.filter(ar => ar.some(el => typeof el === 'string' ? el.indexOf(searchimp) > -1 : false))
    
    Login or Signup to reply.
  2. Use Array.some() to look if there’s a match. Do the match with String::includes():

     const Arrays = [
     [
      { text: " first ", image: "1.jpg", },
      " hello"," world"," ",
    ],
    [
      {text: " second",image: "https://www.wikipedia.org/portal/wikipedia.org/assets/img/Wikipedia-logo-v2.png",},
      " goodbye"," world"," ",
    ],
    [
      { text: " Salut", image: "bass.jpg", },
      " Ca va"," au revoir"," ",
    ],
    ];
    
    const searchimp = 'goo';
    const showArrays = Arrays.filter(arr => arr.some(elem => typeof elem === 'string' && elem.includes(searchimp)));
    
    console.log(showArrays);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search