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}`)
Chukwu3meka
  • 3,547
  • 4
  • 26
  • 44

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
  • 5,330
  • 1
  • 16
  • 34
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,035
  • 3
  • 16
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
  • 4,567
  • 13
  • 30
  • 40