Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter array objet 2 dimensions by text

I need to filter a two dimensional array in JS, I know there is the accumulator could you explain me how to do it please

let listItems = [
  {
    category: false,
    items: [
      { value: 1, label: 'Disabled'},
      { value: 2, label: 'Carole Poland'},
      { value: 3, label: 'Wanda Howard'},
    ],
  },
  {
    category: 'Suggestions',
    items: [
      { value: 4, label: 'Robin Counts'},
      { value: 5, label: 'Alex Doe'},
    ],
  },
  {
    category: 'Batiment',
    items: [
      { value: 6, label: 'Vincent Howi'},
      { value: 7, label: 'Alex Zusk'},
    ],
  }
];

Wanted result after filter by label ‘Alex’

let listItems = [
    { category: 'Batiment', items: [{ value: 7, label: 'Alex Zusk'}] },
    { category: 'Suggestions', items: [{ value: 5, label: 'Alex Doe'}] }
];


<input 
  type="text" 
  id="myInput"
  onkeyup="myFunction()" 
  placeholder="Search.." 
/>

function myFunction() {
     input = document.getElementById("myInput");
   filter = input.value.toUpperCase();
   console.log('Search :', filter);
}

https://jsfiddle.net/z03gjdpo/4/

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  • Using Array#reduce, iterate over the array while updating a list.
  • In every iteration, using Array#filter and String#includes, get items whose label includes the target string. If the latter exist, push a new object to the accumulator with category and filtered items.
const listItems = [
  {
    category: false,
    items: [ { value: 1, label: 'Disabled'}, { value: 2, label: 'Carole Poland'}, { value: 3, label: 'Wanda Howard'} ]
  },
  {
    category: 'Suggestions',
    items: [ { value: 4, label: 'Robin Counts'}, { value: 5, label: 'Alex Doe'} ]
  },
  {
    category: 'Batiment',
    items: [ { value: 6, label: 'Vincent Howi'}, { value: 7, label: 'Alex Zusk'} ]
  }
];
const target = 'Alex';

const filteredListItems = listItems.reduce((list, { category, items = [] }) => {
  const filteredItems = items.filter(({ label }) => label.includes(target));
  if(filteredItems.length > 0) { list.push({ category, items: filteredItems }); }
  return list;
}, []);

console.log(filteredListItems);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading