0

"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?

4
  • 1
    Show us what you've tried. Commented Dec 15, 2021 at 17:41
  • Change your code from arr.push(i); to arr.push(i);arr.push(i); ? Commented Dec 15, 2021 at 17:46
  • @freedom, what's wrong with arr.push(i, i)? Commented Dec 15, 2021 at 17:59
  • @tao nothing at all. If OP is having difficulty determining that 1x .push adds one value and can't determine for themselves that 2x .push adds 2 values, then giving them the simplest solution will help them move along. Commented Dec 15, 2021 at 18:15

2 Answers 2

1

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)
    }`);
});

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

Comments

1

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

1 Comment

Why not array.push(i,i)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.