How to create an array containing 1...N ?

You can create an array containing numbers from 1 to N using a loop or using the Array.from() method. Here's how you can do it with both approaches:

    Using a Loop: You can use a simple loop to push numbers from 1 to N into an array.

javascript

function createArrayFrom1ToN(N) {
  const result = [];
  for (let i = 1; i <= N; i++) {
    result.push(i);
  }
  return result;
}

const N = 10;
const arrayFromLoop = createArrayFrom1ToN(N);
console.log(arrayFromLoop);  // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    Using Array.from(): The Array.from() method can create an array from an iterable object or a mapping function. Here, we'll use it with a mapping function to generate numbers from 1 to N.

javascript

const N = 10;
const arrayUsingArrayFrom = Array.from({ length: N }, (_, index) => index + 1);
console.log(arrayUsingArrayFrom);  // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Both approaches yield the same result—a new array containing numbers from 1 to N. The choice of which method to use often depends on personal preference and code readability.

Comments