简体   繁体   中英

Removing a matching string item from a multidimensional array

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!

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
  )
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM