Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count empty array

I need to count letters of string, I don't know how to count an empty array

    const regex = /[\[\]]/gi;
    const a = str.replaceAll(regex, ' ').trim().split(" ")
    const arr = []
    const arr2 = []
    let newArr
    for(let i = 0; i < a.length; i++) {
       if (a[i].length === 0) {
           arr2.push(0)
       } 
       if (a[i].length !== 0) {
           arr.push(a[i].length)
       } 
    }
    newArr = arr.concat(arr2)
    if (newArr.includes(0)) {
        newArr.pop()
    }
    return newArr.join(", ")

I must get: [Tom][] -> 3, 0 But I get a 3 without zero

like image 300
Derek Avatar asked Nov 01 '25 21:11

Derek


1 Answers

It's not described in the question text, but according to your code, the input string has the format: (\[[a-zA-Z]*\])*.

I would remove the first [ and the last ]. Then, I would split the string by ][.

const str = '[Tom][]';

const substrs = str.substring(1, str.length - 1).split('][');
const lengths = substrs.map(str => str.length);

console.log(lengths.join(', '));