0

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}}
1
  • 2
    1. That's not an Array. 2. jQuery doesn't have arrays, JavaScript has arrays. 3. Have you done any research? :-) Commented Jul 1, 2016 at 17:10

2 Answers 2

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"]

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.
@4castle Indeed it would in that case.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.