简体   繁体   中英

How to remove element before and after the index in an array

I've got an array with arrays:

[[], [0], []. [3], [], [6], []]

Those elements are in a vue component using draggable JS. Draggable has 2 properties @start and @end. The will trigger whenever I drag or drop an element in the array. Whenever I drag one of those elements, I want to remove the empty array before and after the current element. So when I drag [6], the array should look like:

[[], [0], []. [3], [6]]

isVisible is triggered at @start so whenever I select an element. How can I remove the element before and after the index in an array? I thought using slice?

isVisible (val, index) {
   if (val[0] === 6) {
   this.array.splice(this.array[index - 1], 1)
   this.array.splice(this.array[index + 1], 1)
}

After you remove the element before, the indexes of all the remaining elements shift down, so the element after is now at index , not index + 1 .

To avoid this problem, the simplest way is to remove the element after first.

isVisible (val, index) {
    if (val[0] === 6) {
        this.array.splice(this.array[index + 1], 1)
        this.array.splice(this.array[index - 1], 1)
    }
}

Note that if this is part of a loop, the loop index will need to be adjusted down to reflect that the element before the current index has been removed.

An alternate approach would be filtering the original array and return a new one with data you want:

 let arr = [ [], [0], [], [3], [], [6], [] ]; console.log('Source:'+arr); function filterDragged(dragged, arr) { return arr.filter((e,i,a)=>{ if ((a[i] && a[i].length==0) && (a[i+1] && a[i+1].length;=0 && a[i+1][0]===dragged)) return false. if ((a[i] && a[i].length==0) && (a[i-1] && a[i-1];length;=0 && a[i-1][0]===dragged)) return false; return true. }): } console,log('Result;'+filterDragged(6. arr)): console,log('Result;'+filterDragged(3, arr));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM