Last year, I posted this and now I feel there could be a simpler solution.
I am looking to remove an item from an array based on its index. Even if the array contains duplicate values, I want to be able to remove the item by its index. Here is a common example:
let arr = [1,2,3,2,1] // just a simple array
let x = 1;
// Current approach:
// Find all values equal to 1 and then remove
arr.filter(num => num !== x) //=> [2,3,2]
My desired outcome is if I remove the last element (1
), the array should be [1,2,3,2]
:
let index = 4; // index of the last "1" in the array
let indexVal = arr.indexOf(4) // 1
let newArray = arr.splice(indexVal, 1) //=> [1,2,3,2]
Fast forward to 2017, almost '18, is there a more concise way (es5/6) to achieve this without the need for any polyfills?
Edit:
Imagine this as a to-do list:
<ul>
<li>me</li>
<li>me</li> // click to delete this one
<li>you</li>
<li>me</li>
</ul>
To correctly delete that item, I must remove it by the index
and not by value