3

I am creating a page that will filter some suggestions, where the user can vote for the ones that are most interesting to him.

I'm dividing this screen into 3 tabs [Top Rated], [Newest] and [My Votes] When starting the screen I make a call in the database that brings all the suggestions, I do it with axios

axios
      .get("/sugestoes/carregar/xxxx")
      .then(res => {
        this.sugestoesGeral = res.data.sugestoes

        for(var i=0; i < this.sugestoesGeral.length; i++){
          if(this.sugestoesGeral[i].meu_voto === "S"){
            this.meusVotos.splice(1, 0, this.sugestoesGeral[i])
          }
        }

        this.maisVotados     = [...this.sugestoesGeral]
        this.maisNovos       = [...this.sugestoesGeral] 
        this.ordernarArrVotos(this.maisVotados)
      })
      .catch(err => {
        console.log(err);
      });

This way I start my three different arrays from the first call in the database

When the user votes on a suggestion, I reorder the arrays according to their respective tab [Top Rated], [Newest] and [My Votes]

this.moreVoted and this.moreNew arrays are reordered without any problem. However I need to perform other actions with the array this.meusVotes besides simply reordering, I need to check if it removed a vote, if I have done this I need to remove this position from the array and then show it again to the user

To remove a position from the array I am doing the following:

for(var i=0; i < this.sugestoesGeral.length; i++){
        if(this.sugestoesGeral[i].meu_voto === 'N'){
          var length = this.meusVotos.length
          for(var x=0; x < length; x++){
            if(this.meusVotos[x].id_sugestao === this.sugestoesGeral[i].id_sugestao){
              this.meusVotos.splice(x, 1)
            }
          }
        }
      }

console.log(this.meusVotos)

However this way it has no effect and does not remove any position from my array. Just for testing I did as follows:

this.meusVotos.shift()
console.log(this.meusVotos)

But the result is the same, no elements are removed from the array. The most curious thing is that I made a copy of these arrays to test on the browser console and it works without errors. The following example works fine on the console:

Arrays:

sugestoesGeral = [
                    {
                        status_atual: "Em votação",
                        categoria: "Parâmetros",
                        quantidade_votos: 1,
                        meu_voto: "S",
                        id_sugestao: 16,
                        titulo: "Alerta de Valor Excedente por Cliente no MDF-e",
                        data_criacao: "29/01/2020",
                        descricao_resumida: "Alerta de Valor Excedente por Cliente no MDF-e",
                        motivo_rejeicao: "",
                        data_rejeicao: "",
                        data_implementacao: "",
                        data_previsao_execucao: "",
                        data_encerramento_votacao: "",
                        cor: "#b8dbff"
                    },
                    {
                        status_atual: "Em votação",
                        categoria: "Despesas",
                        quantidade_votos: 1,
                        meu_voto: "N",
                        id_sugestao: 7,
                        titulo: "Nova coluna Controle de Despesas",
                        data_criacao: "28/01/2020",
                        descricao_resumida: "Checar vínculo financeiro da Despesa quando vinculada a uma Nota com Financeiro lançado",
                        motivo_rejeicao: "",
                        data_rejeicao: "",
                        data_implementacao: "",
                        data_previsao_execucao: "",
                        data_encerramento_votacao: "",
                        cor: "#b8dbff"
                    }
                ]

meusVotos = [
                    {
                        status_atual: "Em votação",
                        categoria: "Parâmetros",
                        quantidade_votos: 1,
                        meu_voto: "S",
                        id_sugestao: 16,
                        titulo: "Alerta de Valor Excedente por Cliente no MDF-e",
                        data_criacao: "29/01/2020",
                        descricao_resumida: "Alerta de Valor Excedente por Cliente no MDF-e",
                        motivo_rejeicao: "",
                        data_rejeicao: "",
                        data_implementacao: "",
                        data_previsao_execucao: "",
                        data_encerramento_votacao: "",
                        cor: "#b8dbff"
                    },
                    {
                        status_atual: "Em votação",
                        categoria: "Despesas",
                        quantidade_votos: 1,
                        meu_voto: "N",
                        id_sugestao: 7,
                        titulo: "Nova coluna Controle de Despesas",
                        data_criacao: "28/01/2020",
                        descricao_resumida: "Checar vínculo financeiro da Despesa quando vinculada a uma Nota com Financeiro lançado",
                        motivo_rejeicao: "",
                        data_rejeicao: "",
                        data_implementacao: "",
                        data_previsao_execucao: "",
                        data_encerramento_votacao: "",
                        cor: "#b8dbff"
                    }
                ]

for loop to remove the element:

for(var i=0; i < this.sugestoesGeral.length; i++){
        if(this.sugestoesGeral[i].meu_voto === 'N'){
          var length = this.meusVotos.length
          for(var x=0; x < length; x++){
            if(this.meusVotos[x].id_sugestao === this.sugestoesGeral[i].id_sugestao){
              this.meusVotos.splice(x, 1)
            }
          }
        }
      }

Any help will be welcome

3
  • 3
    You can try .filter() array method. array.filter Commented Feb 5, 2020 at 13:16
  • 1
    the .splice( is the proper way to remove an element off an array. I suggest that you check that the value of x is a number and not exceeding the arrays length., it may be that you need to change the x < length to x < this.meusVotos.length as I understand, length is fixed and you modified the array without getting a new length value. the this.meusVotos.length is a live checked variable and the length is static, it stays the same if you modify the array, thus making x out of bounds at some point. Commented Feb 5, 2020 at 13:46
  • @MarkGiblin Da mesma forma alterando o for para this.meusVotos.length o resultado ainda é o mesmo Commented Feb 5, 2020 at 13:49

2 Answers 2

1

I would suggest that you create an computed property for each of these cases: this.moreVoted, this.moreNew and this.meusVotes.

This way your sugestoesGeral becomes the SSOT of those properties.

computed: {
  maisVotados() {
    return this.sugestoesGeral.sort((a, b) => {
      if (a.quantidade_votos > b.quantidate_votos) return 1;
      else if (a.quantidate_votos < b.quantidade_votos) return -1;
      return 0;
    })
  },
  maisNovos() {
    return this.sugestoesGeral.sort((a, b) => {
      let dateParts = a.data_criacao.split("/");
      const dateA = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
      dateParts = b.data_criacao.split("/");
      const dateB = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
      if (dateA > dateB) return 1;
      else if (dateA < dateB) return -1;
      return 0;
    });
  }
},
methods: {
  reordenarSugestoes() {
    this.meusVotos = this.sugestoesGeral.filter((sugestao) => sugestao.meu_voto === 'S');
  }
}
Sign up to request clarification or add additional context in comments.

6 Comments

I need it to do the reorder action only when clicking on a specific button But I tried your suggestion as follows: this.meusVotos = this.sugestoesGeral.filter((sugestao) => sugestao.meu_voto === 'S'); The array has not been changed unfortunately
You'll need to change it on the base array this.sugestoesGeral and all the others will reactively update
I've just now realised I missed some things I will update my answer
@FábioSantos How are you calling the update function? On a method that receives an event perhaps?
@BernadoDuarte I call through a method created in methods ()
|
1

try

for(var i=0; i < this.sugestoesGeral.length; i++){
   if(this.sugestoesGeral[i].meu_voto === 'N'){
      for(var x=0; x < this.meusVotos.length; x++){
         if(this.meusVotos[x].id_sugestao === this.sugestoesGeral[i].id_sugestao){
             this.meusVotos.splice(x, 1);
            }
          }
        }
      }

and see how you get on.

as I explained previously, the .splice() is the proper way to remove an element off an array. I suggest that you check that the value of x is a number and not exceeding the arrays length., it may be that you need to change the x < length to x < this.meusVotos.length as I understand, length is fixed and you modified the array without getting a new length value. the this.meusVotos.length is a live checked variable and the length is static, it stays the same if you modify the array, thus making x out of bounds at some point.

7 Comments

Unfortunately trying the way you mentioned the result is the same
Then I would debug, put in console.log() elements and monitor output at various processing stages to track the bug down. It can be as simple as you have the name convention wrong. as in typo errors are common, I know as I do it all the time.
Here is a thought... ARE YOU ABSOLUTELY SURE that you are using the appropriate method? Its not an OBJECT is it? You use delete obj.property
It is an array of objects, I need to remove it from the array whenever one of the elements is changed from yes to no
Sorry, was busy putting shelves up. Its an array of objects and how was the array or base element created? If it is protected in some way, then it may be your issue. It is hard to say because I have not got the hardware setup to test your code.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.