.split() then .splice() - different results depending on whether I assign split item to new variable then splice it, or not

Sorry if the title of this post is a bit confusing.

Here’s the problem:

I’m converting a string into an array using split(' ').
Then I’m removing the first letter of the new array using .splice(0,1).
This is then output to the screen.

HTML:

    <button onclick="arraySplice()">
       Remove first item from Array with .splice(0, 1)
   </button>
    <p id="array-splice"></p>

JAVASCRIPT:

const fruitsString = "Banana";

If I write the function this way I get the desired result: first letter is removed and the rest of the
array is printed -

        function arraySplice() {
            const newFruitsSplicedArray = fruitsString.split('')
            newFruitsSplicedArray.splice(0,1);
            const output = document.getElementById("array-splice");
            output.innerHTML = newFruitsSplicedArray;
        }

Screen: a,n,a,n,a
Console: ["a", "n", "a", "n", "a"]


But, if I write the function like this I get the opposite result - everything but the first letter is removed.

        function arraySplice() {
            const newFruitsSplicedArray = fruitsString.split('')
            const arrSplice = newFruitsSplicedArray.splice(0,1);
            const output = document.getElementById("array-splice");
            output.innerHTML = arrSplice;
            console.log(arrSplice)
        }

I get:

Screen: B
Console: ["B"]

Could anyone explain why this is happening?

Look at what splice returns. If you set your array to the return value of splice, you’re setting to be whatever was spliced out.

Sorry, don’t quite understand - could you be more specific with reference to those two functions?!

You’re assigning two different things, so you get two different results, they’re completely different.

const newFruitsSplicedArray = fruitsString.split('')
newFruitsSplicedArray.splice(0,1);

say fruitsString is “Banana”.
split into characters, so newFruitsSplicedArray is ['B', 'a', 'n', 'a', 'n', 'a'].
splice is set to remove the first character from that array, so then newFruitsSplicedArray is going to be [ 'a', 'n', 'a', 'n', 'a']

You have an array of characters and you remove the first one from it, then you print that array.


const newFruitsSplicedArray = fruitsString.split('')
const arrSplice = newFruitsSplicedArray.splice(0,1);

say fruitsString is “Banana”.
split into characters, ['B', 'a', 'n', 'a', 'n', 'a'].
arrSplice is an array of what splice returns, ['B'], and you’re assigning that to a variable called arrSplice

You have an array of characters and you take the first one off it and print it.

1 Like

Doh! Yes, I see it now. Thanks for taking the time on this! :slight_smile:

1 Like