Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element from array and return only remaining elements

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;
}
like image 753
André Castro Avatar asked Jan 24 '19 11:01

André Castro


2 Answers

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);
like image 195
Fullstack Guy Avatar answered Sep 24 '22 00:09

Fullstack Guy


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}`);
like image 36
dquijada Avatar answered Sep 22 '22 00:09

dquijada