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.
import pullAt from 'lodash/pullAt'
import dropRight from 'lodash/dropRight'
/**
* I am using a JavaScript module to isolate the code of each snippet.
* In fact it's a Vue.js mixin. Take the code called by the mounted()
* or the snippetXX() function.
*
* I only import only the two Lodash function I use in this snippet. If you want
* to have all the functions call the standart import: import _ from 'lodash'
*/
export default {
methods: {
snippet81 () {
// Open your JavaScript console in order to check the execution of this code.
'use strict'
console.log('—— Vanilla JS —————————————————————————————————————————————————')
const 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! 😁
}
},
mounted () {
if (this.isArticle(81)) {
this.snippet81()
}
}
}
More on Stackoverflow Read the doc More on the web Random snippet