Search code examples
javascriptarraysjsonconcatenation

Displaying unlimited amount of undefined arrays, javascript


Referring to: JavaScript String concatenation behavior with null or undefined values

I tried to display an array created from infinite amount of array of objects and some arrays might be undefined. Is there a nicer way of writing that. My solution for that problem does not look professional.

const theFunction = () => {
    let EveryArrayGoesHere = []
    try {
        EveryArrayGoesHere = EveryArrayGoesHere.concat(array1, array2, array3 ...)
        if (EveryArrayGoesHere) {
            EveryArrayGoesHere = JSON.stringify(EveryArrayGoesHere)
            EveryArrayGoesHere = EveryArrayGoesHere.replace('null,', '')
            EveryArrayGoesHere = EveryArrayGoesHere.replace(',null', '')
            return JSON.parse(EveryArrayGoesHere);
        } else {
            return 'data not availible';
        }
    } catch (e) {
        if (e) {
            console.error('data error', e.message)
        }
    }
}
console.log('array of objects:',theFunction() )

Solution

  • I hope I've correctly understood your question.

    var collector = [];
    var data = [
      [1,2,3],
      undefined,
      [4,5,6],
      [7,8],
      undefined,
      [9]  
    ];
    // console.log('data => ', data);
    data = data.filter(v => { return Array.isArray(v)}).forEach(a => { collector = collector.concat(a) });
    console.log('collector => ',collector);