How to use index()?

Asked

Viewed 512 times

-3

I have the following code:

var addItem = document.getElementById("add-item");
    var formItem = document.getElementById("form-item");
    var itens = [];
    var idItem = 0;
    var idDiv = 0;

    addItem.addEventListener("click", function(){
        var nome = document.getElementById("nome-item");
        var codigo = document.getElementById("cod-item");
        var descricao = document.getElementById("desc-item");
        var qtd = document.getElementById("qtd-item");
        var valor = document.getElementById("valor-item");
        idItem++;

        adicionaItem(idItem, nome, codigo, descricao, qtd, valor);
    });
    function adicionaItem(idItem, nome, codigo, descricao, qtd, valor){
        var novoItem = {};
        novoItem['id'] = idItem;
        novoItem['nome'] = nome.value;
        novoItem['codigo'] = codigo.value;
        novoItem['descricao'] = descricao.value;
        novoItem['quantidade'] = qtd.value;
        novoItem['valor'] = valor.value;

        itens.push(novoItem);

        mostraItens(itens, novoItem);
        console.log(idItem);
    }
    function mostraItens(itens, novoItem){

        var tagLinha = document.createElement("DIV");
        tagLinha.className = "row";
        tagLinha.setAttribute("id", idDiv);
        formItem.appendChild(tagLinha);

        var botaoDel = document.createElement("BUTTON");
        botaoDel.setAttribute("type", "button");
        botaoDel.setAttribute("onclick", "removeItem(itens)");
        botaoDel.textContent = "Excluir";
        tagLinha.appendChild(botaoDel);

        idDiv++;
    }
    function removeItem(itens){

        console.log(itens.indexOf());

    }

In the function log removeItem i would like to find the index of the object with a specific id, but don’t know how to do it. I would like to know how to use the index correctly().

1 answer

4

To remove an element from a array by index, you must use the method splice. An example:

const arr = ['A', 'B', 'C', 'D', 'E'];
arr.splice(3, 1); // Remove o elemento de índice 3 ('D')
console.log(arr);

To find the content in a array object, is not used indexOf. The most recommended is to use the method findIndex, that accepts a function as argument so that you can select the element you want to find the index.

The functioning of findIndex is simple: it will go through all the elements of array, passing the element of each iteration as parameter to the function passed as argument.

If the argument function returns true, the other iterations will be stopped, and the method findIndex return the element index. It is also important to keep in mind that if no element meets the condition, returning true, the findIndex will return -1.

For example to be less confused:

const shopList = [{
  id: 1,
  item: 'Maçã'
}, {
  id: 2,
  item: 'Pêra'
}, {
  id: 3,
  item: 'Banana'
}, {
  id: 4,
  item: 'Café'
}];

// Achar o elemento que tem o ID 3:
const index = shopList.findIndex(function (shopItem) {
  // Realizamos a busca:
  // `findIndex` retornará o índice do primeiro elemento cuja iteração retornar `true`:
  if (shopItem.id === 3) {
    return true;
  }
  
  return false;
});

console.log(index);
console.log(shopList[index]);

// Remover:
shopList.splice(index, 1);
console.log(shopList);

For didactic reasons, I tried to make the above code simpler to understand. Keep in mind, however, that it can be greatly improved:

const shopList = [{
  id: 1,
  item: 'Maçã'
}, {
  id: 2,
  item: 'Pêra'
}, {
  id: 3,
  item: 'Banana'
}, {
  id: 4,
  item: 'Café'
}];

const index = shopList.findIndex(({ id }) => id === 3);
shopList.splice(index, 1);
console.log(shopList);

Reference:

Browser other questions tagged

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