'Removing nickname from localStorage string

I'm trying to check localStorage for a nickname and if it includes the nickname remove it from the localStorage.

window.removeNickname = (n) => {
    const names = localStorage['nicknames'].split(','); // Output = ["NAME 1", "NAME 2", "NAME 3"]
    if (names.includes(n)) {
        // HOW CAN I REMOVE THE NAME FROM THE LOCALSTORAGE HERE AND REPLACE THE LOCALSTORAGE NICKNAMES.
    }
};
    
removeNickname('NAME 2');


Solution 1:[1]

You can try to remove the item from the array with split and set the new array as your nicknames. Splice removes the items from array starting from the index that you mentioned in the first argument and removes as many elements as you set in the second argument.

window.removeNickname = (n) => { 
  const names = localStorage['nicknames'].split(','); // Output = ["NAME 1", "NAME 2", "NAME 3"]
  if (names.includes(n)) {
    localStorage.setItem(nicknames, names.splice(names.indexOf(n), 1));
  }
};

Solution 2:[2]

This is a great use case for localDataStorage, a utility I authored. With localDataStorage you can create and manipulate Array Keys and store the value in localStorage. Some examples:

Create and initialize an Array Key in localStorage called nicknames with 3 element values:

> lds.push( 'nicknames', 'Mac', 'Bill', 'Will' );


Query the Array Key for a certain element:

> lds.contains( 'nicknames', 'Bill' );
  true


Remove an element from the Array Key (specifying a value literal):

> lds.pull( 'nicknames', 'Bill' );


Get the updated key value:

> let newKey = lds.get( 'nicknames' );
['Mac', 'Will']


So your application might go something like this:

const removeNickname = (n) => {
    lds.pull( 'nicknames', n );
    return lds.get( 'nicknames' );
};

const addNickname = (n) => {
    lds.push( 'nicknames', n ); // appends to array
    return lds.get( 'nicknames' );
};

updatedNicknamesArray = removeNickname( 'Tom' );

updatedNicknamesArray = addNickname( 'Tim' );

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Mac