In python, I can remove the first item from array xs like so:
xs = xs[1:]
How could I do that with the following javascript array?
var data = {{data}}
asked Jul 1, 2016 at 17:09
Everyone_Else
3,2745 gold badges34 silver badges58 bronze badges
-
21. That's not an Array. 2. jQuery doesn't have arrays, JavaScript has arrays. 3. Have you done any research? :-)T.J. Crowder– T.J. Crowder2016年07月01日 17:10:31 +00:00Commented Jul 1, 2016 at 17:10
2 Answers 2
The JavaScript splice function, not an specific of jQuery.
var fruit = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];
var removed = fruit.splice(0, 1);
console.log(removed);
console.log(fruit);
The result is ["Orange", "Apple", "Mango", "Kiwi"]
T.J. Crowder
1.1m201 gold badges2k silver badges2k bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
T.J. Crowder
Indeed, this is the other way.
shift returns the value directly, splice will return an array of the values removed. So both do the job, the one you pick depends on what you want to do with the result.castletheperson
splice would be preferred if we were removing more than 1 from the start. It's also similar to the Python version. In this case shift is simpler though.T.J. Crowder
@4castle Indeed it would in that case.
If you want to get the first value out of an array and remove it from the array, you can use Array#shift (MDN | spec):
var a = [1, 2, 3, 4]; // An array
var first = a.shift(); // Remove and return the first entry
console.log(first); // Show the value we got
console.log(a); // Show the updated state of the array
answered Jul 1, 2016 at 17:11
T.J. Crowder
1.1m201 gold badges2k silver badges2k bronze badges
Comments
lang-js