0

I need to add multiple arrays together depending on user's preference some array might appear empty, how do I make sure the array I'm about to concat is not empty

here is my failed code

const num1 = [12,67,100] 
const num2 = [] 
const num3 = [23,191, 58]
const num4 = [23,30]

const numbers = num1.concat(`num${Math.random() * 10}`)
Chukwuemeka Maduekwe
  • 6,687
  • 5
  • 44
  • 67
  • 3
    Create a 2D array (an array of arrays) instead of trying to access variables dynamically. Also, it's unclear what you mean by selecting an based on *user's preference* when you're using `Math.random()` – adiga Feb 24 '20 at 12:06
  • You can simply add check for Array.length, if length is > 0, then only add. – Sarvesh Mahajan Feb 24 '20 at 12:07
  • 4
    Even if the array is empty it should not be an issue as `[1,2].concat([])` is same as `[1,2]` – palaѕн Feb 24 '20 at 12:10
  • what i mean is undefined – Chukwuemeka Maduekwe Feb 24 '20 at 12:59
  • Does this answer your question? "[How do I create dynamic variable names inside a loop?](/q/8260156/90527)", "[Use dynamic variable names in JavaScript](/q/5117127/90527)" – outis Dec 25 '22 at 07:04

3 Answers3

0

Following this answer, converting to 2d array and convert it to a single flat array, seems like the preferred solution

const values = [ [12,67,100], [], [23,191, 58], [23,30] ]

const numbers = [].concat(...values)

console.log(`items count: ${numbers.length}`)

const randomNumbers = numbers.map(num => parseInt(num * Math.random()))
ymz
  • 6,602
  • 1
  • 20
  • 39
0

There you go, easy to understand:

constant numbers;
int randomArray = `num${Math.random() * 10}`;

if (randomArray.length > 0)
{
    numbers = num1.concat(randomArray);
}
feedy
  • 1,071
  • 5
  • 17
0

const num1 = [12, 67, 100]
const num2 = []
const num3 = [23, 191, 58]
const num4 = [23, 30]

const check = `num${Math.random() * 10}`
const numbers = num1.concat(check && check)

console.log(numbers);
double-beep
  • 5,031
  • 17
  • 33
  • 41