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

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'm looking to add new elements that are within a case option in array .

But first check if array finds the same element, to avoid duplicating!

    
asked by anonymous 11.02.2017 / 15:34

3 answers

3

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

Your% check% seems to be wrong. This code will do the same thing 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) 
    
12.02.2017 / 12:17
1

First of all, using switch is not a good idea. In general, switch is something that tends to be easily used improperly and most of the time there is some better resource, few cases where switch is the best alternative.

However, if you really want to insist on using switch , I think you want to select the array size 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 switch can almost always be replaced by something simpler, note that my switch integer could be replaced by this:

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

After some answers given by both Victor Stafusa , followed by colleague handoncloud , I reached the conclusion.

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

This array.pop() function 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 Demo

    
12.02.2017 / 15:30