简体   繁体   中英

Select and deselect multiple items from array

I have a snippet of code here where i have an array that may or may not have keys in it. When the user presses on a 'friend' they add them to a list (array) where they might start a chat with them (add 3 friends to the array, then start a chatroom). The users selected might be toggled on or off.

Current Behavior: i can add/remove one person, but i cant add multiple people to the array at the same time. When i add one person, select another - the first person is 'active', when i remove the first person, the second person automatically becomes active

Expected Behavior: I would like to be able to add multiple people to the array and then remove any of the selected items from the array

onFriendChatPress = (key) => {
  console.log(key)               // this is my key 'JFOFK7483JFNRW'

 let friendsChat = this.state.friendsChat       // this is an empty array initially []

        if (friendsChat.length === 0) {
            friendsChat.push(key)
        } else {

            // there are friends/keys in the array  loop through all possible items in the array to determine if the key matches any of the keys 

            for (let i = 0; i < this.state.selGame.friends.length; i++) {
   
                // if the key matches, 'toggle' them out of the array

                if (friendsChat[i] === key) {
                    friendsChat = friendsChat.filter(function (a) { return a !== key })
                }
                else {
                   return friendsChat.indexOf(key) === -1 ? friendsChat.push(key) : 

                }

            }

        }

}

Help please!

From your code, I was quite confused regarding the difference between this.state.selGame.friends and this.state.friendsChat . Maybe I missed something in your explication. However, I felt that your code seemed a bit too overcomplicated for something relatively simple. Here's my take on that task:

class Game {
  state = {
    friendsChat: [] as string[],
  };

  onFriendToggle(key: string) {
    const gameRoomMembers = this.state.friendsChat;

    if (gameRoomMembers.includes(key)) {
      this.state.friendsChat = gameRoomMembers.filter(
        (member) => member !== key
      );
    } else {
      this.state.friendsChat = [...gameRoomMembers, key];
    }
  }
}

I used typescript because it makes things easier to see, but your JS code should probably give you a nice type inference as well. I went for readability over performance, but you can easily optimize the script above once you understand the process.

You should be able to go from what I sent you and tweak it to be according to what you need

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