-2

I'm learning Javascript and I'm wondering what the most elegant way to convert this: [1,8] into this:[1,2,3,4,5,6,7,8]?

Thanks a lot!

DanielJK
  • 7
  • 1
  • 6
    What have you attempted? Please add the code you've attempted to your question as a [mcve]. ([It will involve a loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration)). – Andy Jun 14 '22 at 22:26
  • 1
    That would basically be a "print all nums from x to y" question with an array as output. If you're asking for the most elegant way I'd recommend finding a working way first. – Jack Bashford Jun 14 '22 at 22:27
  • I'm not quite sure what you mean now that I re-read it. – Joel Hager Jun 14 '22 at 22:27
  • @JoelHager I believe it's 'given two bounds, return all integers between (inclusive) those bounds' or something of the sort. – Jack Bashford Jun 14 '22 at 22:28
  • 1
    Does this answer your question? [How to create an array containing 1...N](https://stackoverflow.com/questions/3746725/how-to-create-an-array-containing-1-n) – pilchard Jun 14 '22 at 22:31
  • 1
    or [how to create array from 17 to 120](https://stackoverflow.com/questions/70067717/how-to-create-array-from-17-to-120) which has links to multiple relevant duplicates – pilchard Jun 14 '22 at 22:32

4 Answers4

1

const argarray = [1, 8]

const countToN = (array) => {
  // init results array
  let res = []
  // start at the first value array[0] go *up to* the second array[1]
  for (let i = array[0]; i <= array[1]; i++) {
    res.push(i)
  }
  // return the result
  return res
}

console.log(countToN([1, 10]))

This would accommodate what you're trying to do, but it's fairly brittle. You'd have to check that it's an array and that it has only 2 values. If you had other requirements, I could amend this to account for it.

Joel Hager
  • 2,990
  • 3
  • 15
  • 44
0

Here's a solution without loops. Note that this only works with positive numbers. It supports arrays of any length, but will always base the result off of the first and last values.

const case1 = [1, 8];
const case2 = [5, 20];

const startToEnd = (array) => {
    const last = array[array.length - 1];
    const newArray = [...Array(last + 1).keys()];

    return newArray.slice(array[0], last + 1);
};

console.log(startToEnd(case1));
console.log(startToEnd(case2));

Here's a solution that works for negative values as well:

const case1 = [-5, 30];
const case2 = [-20, -10];
const case3 = [9, 14];

const startToEndSolid = (array) => {
    const length = array[array.length - 1] - array[0] + 1;

    if (length < 0) throw new Error('Last value must be greater than the first value.');

    return Array.from(Array(length)).map((_, i) => array[0] + i);
};

console.log(startToEndSolid(case1));
console.log(startToEndSolid(case2));
console.log(startToEndSolid(case3));
mstephen19
  • 1,733
  • 1
  • 5
  • 20
0

A simple for loop will do it. Here's an example that has error checking and allows you to range both backwards and forwards (ie [1, 8], and also [1, -8]).

function range(arr) {

  // Check if the argument (if there is one) is
  // an array, and if it's an array it has a length of
  // of two. If not return an error message.
  if (!Array.isArray(arr) || arr.length !== 2) {
    return 'Not possible';
  }

  // Deconstruct the first and last elements
  // from the array
  const [ first, last ] = arr;

  // Create a new array to capture the range
  const out = [];

  // If the last integer is greater than the first
  // integer walk the loop forwards
  if (last > first) {
    for (let i = first; i <= last; i++) {
      out.push(i);
    }

  // Otherwise walk the loop backwards
  } else {
    for (let i = first; i >= last; i--) {
      out.push(i);
    }
  }

  // Finally return the array
  return out;

}

console.log(range([1, 8]));
console.log(range('18'));
console.log(range());
console.log(range([1]));
console.log(range([-3, 6]));
console.log(range([9, 16, 23]));
console.log(range([4, -4]));
console.log(range([1, -8, 12]));
console.log(range(null));
console.log(range(undefined));
console.log(range([4, 4]));

Additional documentation

Andy
  • 61,948
  • 13
  • 68
  • 95
0

Use Array#map as follows:

const input = [1,8],

      output = [...Array(input[1] - input[0] + 1)]
      .map((_,i) => input[0] + i);
      
      
console.log( output );          
PeterKA
  • 24,158
  • 5
  • 26
  • 48