Home > Mobile >  I would like to fill an array with numbers using javascript with a for loop
I would like to fill an array with numbers using javascript with a for loop

Time:12-16

"But I always double the numbers. so [1,1,2,2,3,3 .......] how can you do that? I am looking forward to the answer. " Continuous with a number, the for loop is good. But how do I do it with double numbers?

CodePudding user response:

To get an array to N, use:

let N = 10;
Array.from(Array(N).keys())

To double each value in any array:

[...yourArray.map(n => [n, n])].flat()

So, your solution:

let n = 10;
const a = [...Array.from(Array(n).keys()).map(k => [k, k])].flat()

console.log(a)

To have it starting from 0, not 1, alter the mapping accordingly:

let n = 10;
const a = [
  ...Array.from(Array(n).keys())
    .map(k => [k   1, k   1])
].flat()

console.log(a)

Arguably, the cleanest solution:

function doubleArrayTo(n) {
  const a = [];
  for (i = 1; i <= n; i  ) {
    a.push(i, i);
  }
  return a;
}

console.log(doubleArrayTo(10))


Out of curiosity, I tested their performance. Unsurprisingly, the for loop wins hands down over the spread syntax:

function doubleFor(n) {
  const a = [];
  for (i = 1; i <= n; i  ) {
    a.push(i, i);
  }
  return a;
}
function doubleSpread(n) {
  return [
  ...Array.from(Array(n).keys())
    .map(k => [k   1, k   1])
  ].flat()
}

function run_test(fn, value) {
  const t0 = performance.now();
  fn(value);
  return performance.now() - t0;
}

[1e4, 1e5, 1e6, 1e7].map(value => {
  console.log(
    `(${value}): for => ${
      run_test(doubleFor, value)
    } | spread => ${
      run_test(doubleSpread, value)
    }`);
});

CodePudding user response:

follow this code

var array = [];
for(int i = 0;i <= 10;i  ) {
  array.push(i);
  array.push(i);//again
}

var array = [];
for (let i = 0; i <= 10; i  ) {
  array.push(i,i);
}
console.log(array);

Edit

You can use multi input for array.push(i,i,i,....)

  • Related