Skip to content
Advertisement

How to check if an array has multiple values and push to a new array if a value is met?

I have a list of data that I want to map through and see if an array within each individual item contains a particular set of strings and if it does, would like to push that individual item into a new array.

Some items may contain multiple values so I may need to push this item to multiple new arrays if need be.

To give you an idea of the data, it’s an array of objects with values like the following:

0: {...}
1: {...}
2: {...}
3: {
   id: xyz
   name: test
   tags: ["Mechanical", "Director/Leadership", "Specialist"]
}

The array of strings in which I’m looking for a match in is called ‘tags’

And I have set up a list of empty arrays in my state ready to push an item into when one of these tags values is met, like so:

  const [mechanical, setMechanical] = useState([]);
  const [director, setDirector] = useState([]);
  const [specialist, setSpecialist] = useState([]);


How can I use .map() to iterate through my data and say if this item contains the tag ‘Mechanical’, push that item into the mechanical state array? But if it also contains ‘Specialist’, push that item into the specialist array also? etc. etc.

(there are 6 or 7 strings in this array which i could be looking for a match for.

I’ll then be mapping through the different state in the UI and rendering these items out.

Advertisement

Answer

You can loop through the items and tags, store the items to the specific arrays and finally update the state. Check the code below-

const data = [
  {
   id: 'xyz',
   name: 'test',
   tags: ["Mechanical", "Director", "Specialist"]
  },
  {
   id: 'abc',
   name: 'abc',
   tags: ["Mechanical", "Specialist"]
  }
];

const _mechanical = [];
const _director = [];
const _specialist = [];

for (const item of data) {
  if (item?.tags?.length > 0) {
    for (const tag of item.tags) {
      switch(tag.toLowerCase()) {
        case 'mechanical':
          _mechanical.push(item);
          break;
        case 'director':
          _director.push(item);
          break;
        case 'specialist':
          _specialist.push(item);
          break;
      }
    }
  }
}

console.log(JSON.stringify(_mechanical));
console.log(JSON.stringify(_director));
console.log(JSON.stringify(_specialist));

Finally, update the state with the specific array.

setMechanical(_mechanical);
setDirector(_director);
setSpecialist(_specialist);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement