Deleting an item of a JavaScript array by it's index

Published on 2020-03-07 • Modified on 2020-03-07

This is the kind of thing that it's easy to do with PHP. We can use unset($arr[$idx]); (and keys and preserved). But in JavaScript, this splice() function is quite weird as it can delete items but also insert elements at the same time! Be very careful when using it. Note that the array is mutated and keys are reordered. I have done the same examples with Lodash; they are much straightforward.


<script>
    // Open your JavaScript console in order to check the execution of this code.
    "use strict";
    console.log('—— Vanilla JS —————————————————————————————————————————————————');
    let arr1 = [1,2,3,4,5];
    console.log(arr1);

    // Delete the 1st element, it's index is 0
    arr1.splice(0, 1); // 1st argument: 0 means index 0, second argument: 1 means delete 1 element only
    console.log('Remove item at index 0');
    console.log(arr1);

    // Now delete the last element
    arr1.splice(-1, 1); // -1 means index of the last item, and 1 means delete 1 element only
    console.log('Remove last item');
    console.log(arr1);

    // Same examples with Lodash
    console.log('—— Lodash —————————————————————————————————————————————————————');
    let arr2 = [1,2,3,4,5];
    console.log(arr2);
    console.log('Remove item at index 0');
    _.pullAt(arr2, 0);
    console.log(arr2);

    arr2 = _.dropRight(arr2);
    console.log('Remove last item');
    console.log(arr2);

     // That's it! 😁
</script>