-2

I've been looking for a way to return elements in an array based on a dynamic number. This dynamic number will be the number of required index positions for each array element, if each element can satisfy the required number of index positions (its own position counts towards the requirement) then that element should be returned.

const arr = [1,2,3,4,5,6]

const requiredIndexes = 3

So with the variables listed above I should return [1,2,3,4] because 5 and 6 will not be able to return three index positions.

2
  • 1
    It looks like you're looking for arr.slice(0, arr.length - requiredIndexes + 1)? Commented Nov 10, 2020 at 2:47
  • 1
    I don't understand your question. Are you asking for all the elements that have at least n elements after it in an array? If so, you can simply use arr.splice(-(n-1), 999) Commented Nov 10, 2020 at 2:47

2 Answers 2

0

The Array.prototype.slice might give you some help. Please refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

const arr = [1,2,3,4,5,6]

const requiredIndexes = 3

console.log(arr.slice(0, arr.length - requiredIndexes + 1))

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

1 Comment

This works perfectly. Thank you so much!
0

I am not an expert but I think you would want to iterate up to the position. Are you having the dynamic number be a random number? You may want to also clone your array and use the clone as the worker array. Not sure exactly what you are wanting to do with the array, but you can then slice from the array and the parent array stays unefected.

function pickposition() {
        var randIndex = Math.floor(Math.random() * clone.length);  
        rand = clone[randIndex];
    clone.splice(randIndex,1);
                         }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.