2

I'm wondering if it's possible to pull a certain number of elements out of a Javascript array and insert them into a new array, while using one of the elements as a reference point?

This is what I'm trying to do, imagine I have an array like this:

var firstarray = [ 
475387453,
286235425,
738264536,
196792345,
834532623,
253463455,
535273456];

And then I have a variable that equals the number 286235425:

var element = 286235425;

I have another variable that equals the number 3:

var thenumber = 3;

What I want to do is go through the array, select the 3 elements that come after the ''var element'' number, and store them in a new array named "second array". So with the above example the result should be:

var secondarray = [ 
738264536,
196792345,
834532623];

I've seen some questions that talked about filtering array elements, but I haven't been able to find anything about selecting elements in the above way. Is such a thing even possible? I know it's possible to trim elements from the beginning and end of the array, but as the array will always be a different length whenever the function runs, this method isn't suitable for this problem.

Any help with this would be really appreciated, Thank you in advance!

2 Answers 2

6

You can do this with splice and indexOf

var firstarray = [
  475387453,
  286235425,
  738264536,
  196792345,
  834532623,
  253463455,
  535273456
], element = 286235425,  thenumber = 3;

var secondarray = firstarray.splice(firstarray.indexOf(element)+1, thenumber);
console.log(secondarray)

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

1 Comment

I was about to write the same solution
1

Grab the index where element is in the array using indexOf:

var index = firstarray.indexOf(element);

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Use slice to grab the elements from the array from the next index to the next index + thenumber

var secondarray = firstarray.slice(index + 1, index + 1 + thenumber);

The slice() method returns a shallow copy of a portion of an array into a new array object.

DEMO

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.