Print only the first and last date

Asked

Viewed 39 times

1

An Ajax request returns some information, among them the data_inicio and data_fim of a mandate, but need to display only the dates that are in red, would:

23/12/1936 to 12/12/1944

Como esta atualmente

I need a way to gather and display only them. At the moment I am doing it as follows:

var arr = [];
var per = [];

function printarPeriodo() {
 var html = '<br />';
 for (var i in per) {
     html += '<i class="fas fa-circle fa-xs"></i> &nbsp;' + per[i] + '<br />';
    }
    html += '';

    per = [];
    return html;
    }

function addArray(qual) {
    var pass = false;
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == qual) {
         pass = true;
            }
        }
    if (!pass) {
        arr.push(qual)
    }
}

And using it as follows, within the return of my Ajax:

addArray(json[i].ano_inicio_f);
per.push(json[i].data_inicio_f + ' à ' + json[i].data_fim_f);
  • That function addArray is the same as addToArray?

  • @Sam Yes, I accidentally changed it at the time of passing. I’ve already edited.

2 answers

1


You can do it this way below, but in this case you don’t need the loop for:

var per = ['23/12/1936 a 27/12/1937', '27/12/1937 a 20/12/1940', '20/12/1940 a 22/12/1941', '22/12/1941 a 12/12/1944'];

function printarPeriodo() {
   var html = '<br />';

   // conta o tamanho da array
   var per_len = per.length;
   
   // pega a primeira data do índice [0] da array
   var data1 = per[0].split(" ").shift();
   
   // pega a segunda data do último índice da array
   var data2 = per[per_len-1].split(" ").pop();
   
   // monta a string
   var datas = data1+" a "+data2;

   html += '<i class="fas fa-circle fa-xs"></i> &nbsp;' + datas + '<br />';
   html += '';

   per = [];
   return html;
}

document.write(printarPeriodo());
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous">

1

Instead of just passing the data of the string response, you can save it inside arrays, and these arrays, you save it inside the array per. Thus:

per.push([json[i].data_inicio_f, json[i].data_fim_f]); 

And when adding to the variable html, you could do so:

html += '<i class="fas fa-circle fa-xs"></i> &nbsp;' + per[i].join(" à ") + '<br />';

And to catch the "start" and the "end", you can do:

var per1 = per[0];
var per2 = per[per.length - 1];
//console.log(per1[0] + " à " + per2[per2.length - 1]);

Or

var per1 = per[0];
var per2 = per[per.length - 1];
var inicio = per1[0];
var fim = per2[per2.length - 1];
//console.log(inicio + " à " + fim);

I hope I’ve helped!

Browser other questions tagged

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