Problem using push in JS array

Asked

Viewed 72 times

0

I am entering some dates formatted in a array. When I select per day, the format needs to be "DD/MM", but I get from API "MM/DD", in this case I do the inversion after the push in the array, due to other rules.

The problem occurs only when the date is selected 02/29 until 01/03. The array, somehow, I think it gets lost and inserts twice the date "01/03".

Dice:

[
  {pass_date_time: "03/01", name: "objeto 1" },
  {pass_date_time: "02/29", name: "objeto 2" },
  {pass_date_time: "03/01", name: "objeto 3" },
  {pass_date_time: "03/01", name: "objeto 4" }
]

Code:


      data.forEach(element => {

        if (!Array.includes(element.pass_date_time)) {

          Array.push(element.pass_date_time;

        }
      });

     Array.sort();

The expected result: Array: ["01/03","02/29"]
Result obtained: Array: ["01/03","01/03"]

Primeio loop do foreach

Segundo loop

  • Is that in the backend? there are several ways to solve your problem but first need to know what you really want, your question was not very clear

  • Sorry for not expressing myself well, this is in the frontend, where I get this "DATE" object from an API, what I need is to store the dates in the "ARRAY" in the correct order of the days of the months.

  • got I’ll put my answer I think I understand what you want to do...

  • Reversed. The scope of the question cannot be modified after receiving answers, because if you do, it invalidates them. If you have another question create a new question.

2 answers

3


Have some problems with the code:

  • There is a syntax error on the line Array.push(element.pass_date_time;
  • You are using a native Javascript type Array as if it were a variable.

    To solve the syntax error just put the ) concluding the sentence.

    As for the nomenclature problem, just create an array to receive the result and use more descriptive names in its code.

//Cria o array contendo os dados.
let dados = [{
    pass_date_time: "03/01",
    name: "objeto 1"
  },
  {
    pass_date_time: "02/29",
    name: "objeto 2"
  },
  {
    pass_date_time: "03/01",
    name: "objeto 3"
  },
  {
    pass_date_time: "03/01",
    name: "objeto 4"
  }
]

//Cria o array que irá receber os resultados.
let resultado = [];

//Para cada elemento em dados...
dados.forEach(elemento => {
  //Verifica se ja há um mesmo resultado. 
  if (!resultado.includes(elemento.pass_date_time)) {
    //Se não houver adiciona o elemeto ao resultado.
    resultado.push(elemento.pass_date_time);
  }
});

resultado.sort(); //Oredena o resultado.
console.log(resultado); //Imprime o resultado.

  • Hello Augusto, I made the corrections, but I continue with the same return, I edited the question with the updated code.

  • Click on the run and see the result. https://imgur.com/mcsFmY2

  • Right, I have this result in the array but the positions "inside" it changes: follows image with the result https://imgur.com/0A4BzsX

  • Positions are not what you expect because you are working with strings and not with dates. Which is already something else that involves converting the strings into dates to then sort them

  • Okay, well, then the question is, with any other date, doesn’t this problem occur, you would know how to solve it?

  • It’s just that I told him to turn the strings into dates and then sort them out. Because string are ordered based on the first character, if they are equal the criterion becomes the second and so on. Dates are ordered according to the calendar.

Show 1 more comment

1

you can use the momentjs library that is great in these cases and to solve your array you can do the following: library link: https://momentjs.com/

const newData = data.map(index => {
  return moment(index.pass_date_time).format("DD/MM");
});

in the newData constant you will receive a new array with the values of the dates already converted then just extract them. I hope to have helped.

  • This part of the date conversion I use the Moment, really is very good. The point is that the problem is only in the Push of the Array, where it should insert the two dates, being "02/29" and "03/01", but it inserts twice the "01/03".

  • the array already has some index inside it?

  • No, I’m creating it empty, because it depends on the situation I use with other types of dates.

  • then, this case would be the best situation for you than foreach because it returns a new array, I only saved in a new variable to extract you can create other variables like this: const hourOne = newData[0];
const hourTwo = newData[1]; reminding that this is just a method

  • I updated the question with some images, see if it helps.

Browser other questions tagged

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