Home > Enterprise >  Removing a matching string item from a multidimensional array
Removing a matching string item from a multidimensional array

Time:05-17

I have a multi dimensional array derived from checkbox values, they can have the same strings for all instances of the outer array.

Example Array:

[
    ['One', 'Two', 'Three'],
    ['One', 'Two', 'Three'],
    ['One', 'Two', 'Three'],
]

When I call the function, I am passing an index number which represents which one of the inner arrays I want to address. For instance, if the user unchecked the checkbox representing 'Two' in the 1 index, I'd want the multi dimensional array to change to this.

 [
        ['One', 'Two', 'Three'],
        ['One', 'Three'],
        ['One', 'Two', 'Three'],
 ]

I am having trouble writing this function. This is in React and the snippet to address this is currently like this:

setCheckedValues(prevArray => {
          const newItemArray = prevArray.slice()
          const newItemArrayFiltered = [...newItemArray, newItemArray[index].filter(name => name !== event.target.name)]
          return newItemArrayFiltered
        })

I've searched a lot and am stuck as to how to remove a string in only one of the inner arrays. Thanks for any assistance!

CodePudding user response:

A fairly standard way to handle this is to slice() around the index.

setCheckedValues(prevArray => {
  return [
    ...prevArray.slice(0, index),
    prevArray[index].filter(name => name !== event.target.name),
    ...prevArray.slice(index   1)
  ];
});

With an alternative being to map() over the array checking for the matching index and returning the updated value appropriately.

setCheckedValues(prevArray => prevArray
  .map((arr, i) =>
    i === index
      ? arr.filter(name => name !== event.target.name)
      : arr
  )
);
  • Related