I need to remove one element from an array and return only the remaining elements.
I tried with splice
and filter
but can't get it to work.
With splice
it only returns the removed element, I need the opposite.
var parse_obj = JSON.parse(document.getElementById('imagens').value);
function rImagem(data){
data = data - 1;
document.getElementsByClassName("btn_remover")[data].style.display = 'none';
parse_obj2 = parse_obj.splice(parse_obj.findIndex(e => e.data,1));
new_string = JSON.stringify(parse_obj2);
document.getElementById('imagens').value = new_string;
}
In your scenario you can use filter
to filter the indexes you don't want in the resulting array. The first param of the callback you pass in the filter is the current element ele
and the second is the index of the current element idx
:
parse_obj2 = parse_obj.filter((ele, idx) => idx !== parse_obj.findIndex(e => e.data,1));
Here, lets say I want to remove the element at the third index so I would compare the current index in the filter function callback with the index of the element I want to remove. It will result in a new array with all the elements of the original array only without the element whose index I wanted to remove.
var indexToRemove = 2;
var arr = [1, 2, 3, 4, 5];
var result = arr.filter((data, idx) => idx !== indexToRemove );
console.log(result);
The same result cam be obtained through splice
also.
parse_obj.splice(parse_obj.findIndex(e => e.data,1), 1); //parse_obj is one element less.
Here is the demo:
var indexToRemove = 2;
var arr = [1, 2, 3, 4, 5];
arr.splice(indexToRemove, 1); //removes only the third element and modifies the original array in place.
console.log(arr);
Array#splice
is actually what you are looking for. The problem is, splice doesn't return the new array, it removes the element(s) from the array and returns the deleted elements. However, in the original array you will have the same elements except the removed ones.
let array = [1, 2, 3, 4, 5]
console.log(`Array elements before splice: ${array}`);
console.log(`Deleted elements: ${array.splice(1, 2)}`);
console.log(`Array elements after splice: ${array}`);
If you don't wish to modify the original array, though, you can always use filter:
let array = [1, 2, 3, 4, 5];
let toDelete = [2, 4];
console.log(`Original array elements: ${array}`);
console.log(`Elements to delete: ${toDelete}`);
let newArray = array.filter(n => !toDelete.includes(n));
console.log(`Array elements after splice: ${newArray}`);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With