-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.

codenoob9000
  • 47
  • 1
  • 7
  • 1
    It looks like you're looking for `arr.slice(0, arr.length - requiredIndexes + 1)`? – Nick Nov 10 '20 at 02: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)` – mankowitz Nov 10 '20 at 02:47

2 Answers2

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))
Jay
  • 34
  • 4
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);
                         }
Ed Nolan
  • 62
  • 7