Home > Mobile >  Javascript - Numeric input to obtain variable length array data
Javascript - Numeric input to obtain variable length array data

Time:11-14

I have a dozen arrays (hypothetically) and each has a completely different length. Is there a way that I can name them such that a numeric input into a function will return an array corresponding to that specific number?

This makes no sense so here's kinda what I want:

var dQw4w9WgXcQ;
const array1 = [1,1,1,1,1,1,1,1,1,1];
const array2 = [1,2,3,4];
const array3 = [1,3,6];

function getArray(id){
    output = constNamed('array'   id);
}

//getArray(2) sets dQw4w9WgXcQ to [1,2,3,4]

and yes, dQw4w9WgXcQ is just something I totally typed on accident

CodePudding user response:

USING OBJECT

1) You can creat an object that contain all arrays as:

const arrays = {
  array1,
  array2,
  array3,
};

2) Assign the result getArray(2) to dQw4w9WgXcQ by just returning the array from object.

return arrays[`array${id}`];

var dQw4w9WgXcQ;
const array1 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
const array2 = [1, 2, 3, 4];
const array3 = [1, 3, 6];

function getArray(id) {
  const arrays = {
    array1,
    array2,
    array3,
  };
  return arrays[`array${id}`];
}

dQw4w9WgXcQ = getArray(2);
console.log(dQw4w9WgXcQ);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

NOTE: If you want to set value to dQw4w9WgXcQ directly after the invocation of the function getArray(2)

var dQw4w9WgXcQ;
const array1 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
const array2 = [1, 2, 3, 4];
const array3 = [1, 3, 6];

function getArray(id) {
  const arrays = {
    array1,
    array2,
    array3,
  };
  dQw4w9WgXcQ = arrays[`array${id}`];
}

getArray(2);
console.log(dQw4w9WgXcQ);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

USING ARRAY

var dQw4w9WgXcQ;
const array1 = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
const array2 = [1, 2, 3, 4];
const array3 = [1, 3, 6];

function getArray(id) {
  const arrays = [array1, array2, array3];
  return arrays[id - 1];
}

dQw4w9WgXcQ = getArray(2);
console.log(dQw4w9WgXcQ);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Have one array contain all the arrays. You can then pass that array into the function as an argument along with the id, and use find to return the array at the index of id - 1 (because indexes are zero-based). If find can't meet the condition it will return undefined.

const arr = [
  [1,1,1,1,1,1,1,1,1,1],
  [1,2,3,4],
  [1,3,6]
];

function getArray(arr, id){
  return arr.find((a, index) => index === id - 1);
}

console.log(getArray(arr, 2));
console.log(getArray(arr, 4));
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Note all we're doing here is assigning

  • Related