-3

I have a array with 18 elements (may vary, but only is multiples of 6), I want to assign these 18 elements to 6 variables

lets say the array is

array = ["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18"]

and the variables are

var1, var2, var3, var4, var5, var6

how do I assign the values from the array in to these variables such that for the first time

var1 =1, var2=2, var3=3, var4=4, var5=5, var6=6

and the second time

var1 =7, var2 = 8, var3 = 9, var4 = 10, var5 = 11, var6 = 12

and so on

the length of the array is variables, but it will always be in a multiple of 6

4
  • 3
    Frankly, don't. Any time you want to deal with a set of sequentially named variables, you should be using an array in the first place. The smells of being an XY problem. Commented Sep 2, 2021 at 7:25
  • We usually do the opposite. "I have 18 ugly independent variables, how do I arrange them elegantly in an array?" Commented Sep 2, 2021 at 7:26
  • You could use destructuring assignment, e.g. var [var1, var2, var3, var4, var5, var6] = array; console.log(var4); Commented Sep 2, 2021 at 7:27
  • Does this answer your question? JavaScript: Split array into individual variables Commented Sep 2, 2021 at 7:28

1 Answer 1

2

You can slice your array and use array destructuring:

const array = ["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18"];
for (let i = 0; i < array.length; i += 6) {
  const [var1, var2, var3, var4, var5, var6] = array.slice(i, i + 6);
  console.log(var1, var2, var3, var4, var5, var6);
}

or better

const array = ["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18"];
for (let i = 0; i < array.length; i += 6) {
  const slice = array.slice(i, i + 6);
  console.log(...slice);
}

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

Comments

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.