Javascript: select all elements except one from an array using slice ()?

Let's say I have this array:

var myarray = [a, b, c, d, e]; 

I want to select every element in an array except c.

 var myselection = myarray.slice(3,5); 

This selects only d and e. I would have to do:

 var myselection = myarray.slice(3,5) + myarray.slice(0,2); 

This selects d, e, a and b, BUT the output is not used as a selector, since myselection is now written without a comma between e and a: "d, ea, b"

Do you know how to solve this? Maybe with negative numbers?

Many thanks for your help!!! Lee

+6
source share
3 answers

Use concat:

 myarray.slice(3,5).concat(myarray.slice(0,2)) 

this is evaluated by the array [d,e,a,b] .

Of course, if you know that you just want to delete an array element with index 2, follow these steps:

 myarray.splice(2,1) 

myarray now [a,b,d,e] .

+9
source

Instead, you can splice :

 arr = ['a','b','c','d','e']; arr.splice(2,1); --> arr == ['a','b','d','e']; 

if you don't want to bind to the original array, you can slice make a copy, then splice

 arr = ['a','b','c','d','e']; var selector = arr.slice(); selector.splice(2,1); --> selector == ['a','b','d','e']; 
+2
source

Use splicing:

 myArray.splice(key, 1); 

it removes this unwanted line.

+1
source

All Articles