Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Select all but one item from array with slice()?

Let's say I have this array:

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

I want to select every item in the 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 usable as a selector, since myselection is now written without a comma in between e and a: "d,ea,b"

Do you know a way to solve this? Maybe with negative numbers?

Thanks a lot for your help!!! Lee

like image 851
LeeCanvas Avatar asked Dec 13 '13 23:12

LeeCanvas


2 Answers

Use concat:

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

this evaluates to the array [d,e,a,b].

Of course, if you know you just want to remove array element with index 2, then do:

myarray.splice(2,1)

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

like image 163
Matt Avatar answered Sep 19 '22 18:09

Matt


You can splice instead:

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

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

arr = ['a','b','c','d','e'];
var selector = arr.slice();
selector.splice(2,1);
--> selector == ['a','b','d','e'];
like image 24
Patrick Gunderson Avatar answered Sep 19 '22 18:09

Patrick Gunderson