Print only the first and last date

1

Ajax request returns some information, including data_inicio and data_fim of a command, however I need to display only dates that are in red, it would be:

  

23/12/1936 à 12/12/1944

Ineedawaytomergeanddisplayonlythem.AtthemomentI'mdoingthis:

vararr=[];varper=[];functionprintarPeriodo(){varhtml='<br/>';for(variinper){html+='<iclass="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);
    
asked by anonymous 19.12.2018 / 18:29

2 answers

1

You can do this below, but in this case you do not need the for loop:

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">
    
19.12.2018 / 19:03
1

Instead of just passing the response data into string, you can save it within arrays, and these arrays, you store inside the array per . This way:

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

And at the time of adding to the variable html , you could do this:

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

And to get the "start" and "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 have helped!

    
19.12.2018 / 19:07