Kamran Poladov
Kamran Poladov

Reputation: 490

User inputs exact number of elements into an array

I need to limit the number of elements within the array using separate function with arguments N and x where N is the number of elements within the array x.

First, user enters N; second, exactly N elements into an array x

Upvotes: 0

Views: 65

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386550

You could take the length for a new array and map all inputs.

function execute(length) {
    return Array.from({ length }, (_, i) => prompt('Enter value at index ' + i + ':'));
}

console.log(execute(3));

Upvotes: 1

ibrahim tanyalcin
ibrahim tanyalcin

Reputation: 6491

below will give you the part you need, if the array is not long enough, it will be populated with undefined:

function giveMeNofX(N,x) {
    return (x instanceof Array ? x : []).slice(0,N).concat(Array.apply(null,Array(N))).slice(0,N)
}

giveMeNofX(2,[1,2,3]) //1,2
giveMeNofX(100,[1,2,3]) //1,2,3,undefined.....

Based on what you want, freeze or seal the returned array.

Upvotes: 0

Related Questions