Search for array containing string and number

Asked

Viewed 120 times

3

Hello, I have an array with the following extrusion

ddd: [
    'SP', 11, 12, 13, 14, 15, 16, 17, 18, 19,
    'RJ', 21, 22, 24, 'ES', 27, 28,
    'MG', 31, 32, 33, 34, 35, 37, 38,
    'PR', 41, 42, 43, 44, 45, 46, 'SC', 47, 48, 49,
    'RS', 51, 53, 54, 55,
    'TO', 63, 'GO', 61, 62, 64, 'MT', 65, 66, 'MS', 67, 'AC', 68, 'RO', 69,
    'BA', 71, 73, 74, 75, 77, 'SE', 79,
    'PE', 81, 87, 'AL', 82, 'PB', 83, 'RN', 84, 'CE', 85, 88, 'PI', 89, 86,
    'PA', 91, 93, 94, 'AP', 92, 96, 'RR', 95, 'AM', 97, 'MA', 98, 99,
    'DF'
  ]

And I check if the ddd that I typed is valid this way:

ddd.map(String).includes(value.substring(0, 2)))

This works, the question is, is there a way to filter when checking?

Example:

1) saber ddd = ddd.map(String).includes(value.substring(0, 2)))
2) saber estado = ddd.includes(value))

In this case, example 1 and 2 will work perfectly if I request value = 11 or value equal to SP because the 2 are in extrusion, what I would like to know is the following, would be to locate SP I return only the Ddds that follow from SP ie 11, 12, 13, 14, 15, 16, 17, 18, 19 or of any other State.

Example:

value = 'RJ'
retorno = ddd.includes(value)) // imprime true pois RJ existe
retornoDDD = naoseiseepossivel // como eu retornaria 21, 22, 24 nesta variável?

1 answer

6


Like your array is composed of string and the numbers then you can do as follows:

1 - Find the state index with the function index.

2 - Get the following numbers from the state position until there is another one string, indicating that the Ddds of that sought state ended.

You can do this by checking the data type of the array through the operator typeof, that returns the type in a string.

The function would look like this:

var value = 'RJ'
var retorno = ddd.includes(value));
var retornoDDD = retornarDDD(value);

function retornarDDD(estado) {
    var numerosDDD = [];
    var pos = ddd.indexOf(estado) + 1;

    for (var i = pos; i < ddd.length; i++) {
        if (typeof ddd[i] == 'number') {
            numerosDDD.push(ddd[i]);
        } else {
            break;
        }
    }

    return numerosDDD; // Retorna [21, 22, 24]
}

If there is an invalid status symbol in your array, it will return empty.

  • 2

    perfect, I imagined something like this, take what comes between 2 strings, so I assembled with this structure, there are 2 structures, one for ddd and one for state and then I united the two organizing it this way, I just didn’t know how I would do or if it was possible, but even if it wasn’t, i had 1 array instead of 2 but I was happy that it is possible and works very well, its function is very simple and easy to understand, very cool, thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.