从数组中移除元素并返回剩余元素

19

我需要从数组中删除一个元素并返回剩余的元素。

我尝试使用 splicefilter 但无法使其正常工作。

使用 splice 只会返回已删除的元素,但是我需要相反的结果。

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;
}

2
为什么不直接使用 parse_obj.splice() 会直接在原数组上进行修改,所以一旦你运行了 parse_obj.splice,它就会是已经移除了该项的数组。 - VLAZ
splice返回已删除元素的数组。你能添加随机数据吗?filter应该可以工作。 - Muhammad Usman
splice() method returns the deleted element from the array. You are trying to assign this deleted element in the array parse_obj2. What you should do is not assign anything to the variable parse_obj2 and use the parse_obj array as it is.parse_obj.splice(parse_obj.findIndex(e => e.data,1));new_string = JSON.stringify(parse_obj2); - Srishti Gupta
6个回答

12

在您的场景中,您可以使用filter方法来过滤掉结果数组中不需要的索引。传递到filter方法回调函数的第一个参数是当前元素ele,第二个参数是当前元素的索引idx:

parse_obj2 = parse_obj.filter((ele, idx) => idx !== parse_obj.findIndex(e => e.data,1));

假设我想要移除第三个索引位置上的元素,那么我将在 filter 函数回调中比较当前索引和我想要移除的元素的索引。这将导致一个新的数组,它包含原始数组中所有的元素,但不包括我想要移除的索引位置上的元素。

var indexToRemove = 2; 
var arr = [1, 2, 3, 4, 5];
var result = arr.filter((data, idx) => idx !== indexToRemove );
console.log(result);

也可以通过splice方法获得相同的结果。

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);


6
Array#splice 是您要寻找的方法。问题在于,splice 不会 返回 新数组,它会从数组中删除元素并返回已删除的元素。但是,在原始数组中,除了被删除的元素外,您将拥有相同的元素。

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}`);

如果您不想修改原始数组,那么您可以使用过滤器:

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}`);


3
    function remove(arr,index){
    return arr.slice(0,index).concat(arr.slice(index+1,9))
    }
    
   // remove(<your array over here>,<the index of the element that you want to remove>) 
   // ex -   
    remove(myarray,0);

希望这能帮到你。

1

嘿,我找到了一种简单的解决方案,不使用splice(),而是使用解构。

const myArr = [1,2,3,4,5,6,7,8,9,10];

function removeFirst(array){
const [a, ...arr] = array; //a is never returned
return arr;
}

0
  var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
    var filtered = array.filter(function(value, index, arr){ 
        return value > 5;
    });
    //filtered => [6, 7, 8, 9]
    //array => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

2
虽然这段代码可能回答了问题,但提供关于它是如何解决问题的方式和/或原因的额外上下文会提高答案的长期价值。 - Sven Eberth

0

你只需要知道如何使用splice。希望以下内容能回答你的问题。

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// Inserts at index 1
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1,"May");
// Replaces 1 element at index 4
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April", "May"]


months.splice(4, 1);
// Replaces 1 element at index 4
console.log(months);
// Expected output: Array ["Jan", "Feb", "March", "April" ]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接