How to insert a new value into an array without duplicating through the switch case?

Asked

Viewed 1,185 times

0

One of my attempts so far has been:

array = [1, 2, 4, 5];

definir = function() {
    switch (array) {

        case (array > 1):
            array.push(1);
            break;

        case (array > 2):
            array.push(2);
            break;

        case (array > 0):
            array.push(3);
            break;
    }

    // Comparar elementos duplicado dentro de um vetor
    var checar = array.filter(function(valor, i) {
        return array.indexOf(valor) == i;
    })

    alert(checar);
}
<button onclick="definir();">Definir e Verificar</button>

I am looking to include new elements that are within an option case in the array.

But first check whether in the array the same element is found to avoid duplicating!

  • 1

    Why You Need the Switch?

  • @Thiagosantos Experiment in a personal project, nothing more.

3 answers

3


Just check if the value obtained does not exist in the collection (as the title already says), then pull it directly into it.

Your verification of the checar seems to be wrong. This code will do the same goal as yours, except it will avoid duplicating the addition of existing values.

Edit: Now that I know your test goal, switch conditions have become unnecessary.

var array = [1, 2, 4, 5];
var valor = 3;

var existe = array.indexOf(valor) >= 0;
if (existe) {
  alert('O número ' + valor + ' já existe na coleção.');
  // return
} else {
  array.push(valor);
}
// !existe && array.push(valor) 

1

First to use the switch so it’s not a good idea. In general, the switch is something that tends to be easily used improperly and most of the times there is some better resource, there are few cases where the switch is the best alternative.

However, if you really want to insist on using the switch, I think you want to select the size of the array with it. And so what you want is this:

array = [1, 2, 4, 5];

definir = function() {

    switch (array.length) {

        case 1:
            array.push(1);
            break;

        default:
            array.push(2);
            break;

        case 0:
            array.push(3);
            break;
    }

    // Comparar elementos duplicado dentro de um vetor
    var checar = array.filter(function(valor, i) {
        return array.indexOf(valor) == i;
    });
    alert(checar);
}
<button onclick="definir();">Definir e Verificar</button>

To demonstrate that the switch can almost always be replaced by something simpler, note that my switch whole could be replaced by this:

array.push([3, 1, 2][array.length > 2 ? 2 : array.length]);

1

After a few responses given both by Victor Stafusa, followed by the colleague handoncloud, I have come to the final conclusion.

Let’s see how to check if the value exists in the collection of array before even inserting the new element directly into it.

That function array.pop() will aim to avoid duplicating the addition of existing values.

array = [];

function definir(valor) {
    switch (valor) {
	    case '':
		    document.getElementById('txt').innerHTML = 'Nenhum valor informado';
		    break;
	    default:
		    array.push(valor);
		    break;
}

     if (valor != array.length) {
	     alert('O número ' + valor + ' já existe na coleção.');
	     array.pop(valor);
    }

     document.getElementById('txt').innerHTML = 'Coleção: ' + array + '<br>Quantidade de valores: ' + array.length

}
    <select id="" onchange="definir(this.value);">
        <option value="">-- Selecione --</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>
    
    <br/>
    
    <span id="txt">Nenhum valor informado</span>

w3schools - External demonstration

Browser other questions tagged

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