Jasmin Jasmin - 7 months ago 20
Javascript Question

how to sort dates in jquery

I am having dates on x axis in d3.js graph which are coming from date picker and the dates chosen form date picker gets displayed on x axis but are not sorted ..i want to sort those dates .please suggest something
here is my html

<!doctype html>
<html>

<head>
<meta charset="UTF-8">
<meta content="utf-8" http-equiv="encoding">

<title>D3</title>
<!-- <link rel="stylesheet" type="text/css" href="mystyle1.css" /> -->

<style>
body {
color: #000;
}

.axis {
font: 10px sans-serif;
}

.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}

.bar {
fill: steelblue;
}

.bar:hover {
fill: brown;
}
</style>

<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="123.js" type="text/javascript"></script>

<script>
var thisIsGlobal;
</script>

</head>
<script src="http://d3js.org/d3.v3.min.js"></script>

<body>
<div id="chart"></div>
<div align="center">
From : <input type="date" name="field1" id="field1" /> To : <input type="date" name="field2" id="field2" /><br /><br />
<input type="button" onclick="render(true)" value="Submit" />
</div>

<script>
var jsonURL = 'avb.json';

var myData = [];
var utc=[];

var margin = {
top: 20,
right: 0,
bottom: 80,
left: 40
};
var width = 500 - margin.left - margin.right;
var height = 300 - margin.top - margin.bottom;

var xScale = d3.scale.ordinal().rangeRoundBands([0, width], .1);
var yScale = d3.scale.linear().range([height, 0]);
var hAxis = d3.svg.axis().scale(xScale).orient('bottom').tickFormat(d3.time.format("%Y-%m-%d"));
var vAxis = d3.svg.axis().scale(yScale).orient('left');
var tooltip = d3.select('body').append('div')
.style('position', 'absolute')
.style('background', '#f4f4f4')
.style('padding', '5 15px')
.style('border', '1px #333 solid')
.style('border-radius', '5px')
.style('opacity', 'o');

function getDates() {
return [document.getElementById('field1').value, document.getElementById('field2').value];
}

function render(filterByDates) {

d3.select('svg').remove();

if (filterByDates) {
var date1 = new Date(document.getElementById('field1').value);
var date2 = new Date(document.getElementById('field2').value);

myData = myData.filter(function(d) {
return d.date >= date1 && d.date <= date2;
});
}

xScale.domain(myData.map(function(d) {

return d.date;
}));

yScale.domain([0, d3.max(myData, function(d) {
return d.thisIsGlobal;
})]);

var svg = d3.select('#chart').append('svg')
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg
.append('g')
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(hAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", "-.55em")
.attr("transform", "rotate(-90)");

svg
.append('g')
.attr("class", "yaxis")
.call(vAxis)

svg
.selectAll(".bar") //makes bar
.data(myData)
.enter().append("rect")
.attr("class", "bar")
.style("fill", "steelblue")
.attr("x", function(d) {
return xScale(d.date);
})
.attr("width", xScale.rangeBand())
.attr("y", function(d) {


return yScale(d.thisIsGlobal);
})
.attr("height", function(d) {

console.log("as",d.thisIsGlobal);
return height - yScale(d.thisIsGlobal);
})
.on('mouseover', function(d) {
tooltip.transition()
.style('opacity', 1)

tooltip.html(d.value)
.style('left', (d3.event.pageX) + 'px')
.style('top', (d3.event.pagey) + 'px')
d3.select(this).style('opacity', 0.5)
})
.on('mouseout', function(d) {
tooltip.transition()
.style('opacity', 0)
d3.select(this).style('opacity', 1)
});
}

d3.json(jsonURL, function(data) {

myData = data;
myData.forEach(function(d) {

d.date = new Date(d.date);

// convert GMT to UTC
d.date =new Date(d.date.getTime() + (d.date.getTimezoneOffset() * 60000));

d.name = +d.name;
console.log(d.date,"Gt date");



});

//myData.data.sort();
console.log(myData,"hello j");

render(false);
});
</script>

<label> List of Tables : </label><br>
<form name="myform" id="myForm">
<div style="height: 30px; width: 50px;">
<select id="dropdown1"></select>
</div>
<style>
#listbox {
display: none;
}
#listbox {
position: relative;
}
</style>


<div style="margin-left: 150px; margin-top: -30px; height: auto;">
<select id="listbox", multiple></select>
</div>

</form>
</body>
</html>
this is my jquery

$(document).ready(function() {
$.ajax({
url: "avb.json",
dataType: "json",
success: function(obj) {
console.log("obj--", obj)
var jsObject = obj;
var usedNames = [];
$('<option>', {
text: 'Select your Option',
value: '',
selected: 'selected',
disabled: 'disabled',
location: 'fixed'
}).appendTo('#dropdown1')
$.each(obj, function(key, value) {
if (usedNames.indexOf(value.name) == -1) {
$("#dropdown1").append("<option value=" + key + ">" + value.name + "</option>");
usedNames.push(value.name);
}
});
$('#dropdown1').change(function() {
$('#listbox').toggle(this.value != "");
});

$('#dropdown1').change(function() {

$('#listbox').empty();

$('<option>', {
text: 'Select your List Option',
value: '',
selected: 'selected',
disabled: 'disabled'
}).appendTo('#listbox');

var selection = $('#dropdown1 :selected').text();
console.log("as".selection);
$.each(jsObject, function(index, value) {
console.log("%o",value)
if (value['name'] == selection) {
var optionHtml = '';
for (var i = 1; i <=20; i++) {

var attr = 'attr' + ('000' + i).substr(-3);
var val = 'val' + ('000' + i).substr(-3);

optionHtml += '<option value="' + attr + '" data-val="'+value[val]+'">' + value[attr] + '</option>';

}


$("#listbox").css("width", "500px")

$("#listbox").css("height", "300px")
$('#listbox').append(optionHtml);
return false;
}
var selectedOption = $(this).find('option:selected');
console.log(selectedOption);

});

});
$("#listbox").on("click", function() {

console.log("asd", $('#listbox option:selected').attr('data-val'));
var thisIsGlobal = $('#listbox option:selected').attr('data-val')
$(".bar").attr("y",thisIsGlobal)
console.log("test", $(".bar").attr("y",thisIsGlobal))
$(".bar").attr("height",'10')


})
}
});
});

Answer

After you've mapped the dates to an array, you can just sort that array

xScale.domain(
    myData.map(function(d) {
        return d.date;
    }).sort(function(a,b) {
        return a > b;
    })
);
Comments