0

I am aware pop() will remove the last element in a JS array, and that shift() will remove the first one, and that slice() lets you remove elements from an array - and that you can specify what position to start at, and how many to remove, like so:

let cities = ["New York", "Tokyo", "Perth", "Helsinki"];
cities.splice(2, 2);
console.log(cities);

What I'm wondering is if there's a method you can use to start at a certain array position, and remove any additional elements beyond that number?

1

3 Answers 3

3

Yeah, splice. Just do not provide the second argument

From Docs

deleteCount Optional

If deleteCount is omitted, or if its value is larger than array.length - start (that is, if it is greater than the number of elements left in the array, starting at start), then all of the elements from start through the end of the array will be deleted.

let cities = ["New York", "Tokyo", "Perth", "Helsinki"];
cities.splice(2)

console.log(cities)

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

1 Comment

Ah, nice. Didn't realize this was an option.
0

Just use splice provide the initial index only it will assume you want every other value till the end of the array

Comments

0

If you don't want to change original array use slice() by passing 0 as first argument

let cities = ["New York", "Tokyo", "Perth", "Helsinki","Landon"];
let number = 1
console.log(cities.slice(0,number));

You can do that using splice() if you want to modify original array.

let cities = ["New York", "Tokyo", "Perth", "Helsinki","Landon"];
let number = 1
cities.splice(number); 
console.log(cities);

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.