I'm trying to figure out why the values in my chart are not coming out correctly. When I log the values of learningLanguages[j].count++
as it is looping they are accurate. However, when I log n
in the map function in the chart $.map(nativeLanguages, function(n) {...})
, the counts are all incorrect (and seemingly arbitrary)
var getLanguages = $.get('/languages.json', function(languages){
// top level language arrays
learningLanguages = []
nativeLanguages = []
// object constructor that correctly formats the language objects
function Language(lang) {
this.language = lang;
this.count = 0;
}
// Loop through the languages, create an object for each, push to top level language arrays
for(i = 0; i < languages.length; i++) {
currentLanguage = new Language(languages[i].language)
learningLanguages.push(currentLanguage)
nativeLanguages.push(currentLanguage)
}
});
// once the languages call is complete find signed-in user's info
getLanguages.done(function() {
$.get('/users.json', function(response) {
// console.log(response)
// adds the total number of users to the DOM
var numberOfUsers = response.length
$('#userCount').append('<h1>Total Users: ' + numberOfUsers + '</h1>')
// find the number of approved users
// var numberApproved = 0
// for (i = 0; i < response.length; i++) {
// if (response[i].approved === true) {
// numberApproved++
// }
// }
// Add the number of approved users to the DOM
// $('#userCount').append('<h1>Total Approved Users: ' + numberApproved + '</h1>')
// search for the language in the array and increase the count for that language
for (i = 0; i < response.length; i++) {
var userLearningLanguage = response[i].learning_language
for (j = 0; j < learningLanguages.length; j++) {
if (learningLanguages[j].language === userLearningLanguage) {
learningLanguages[j].count++
}
}
}
// search for the language in the array and increase the count for that language
for (i = 0; i < response.length; i++) {
var userNativeLanguage = response[i].native_language
for (j = 0; j < nativeLanguages.length; j++) {
if (nativeLanguages[j].language === userNativeLanguage) {
nativeLanguages[j].count++
}
}
}
var ctx = $("#languageComparisonChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels:
$.map(learningLanguages, function(n) {
return n.language
}),
datasets: [{
label: '# of Learners',
data: $.map(learningLanguages, function(n) {
return n.count
}),
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1
},
{
label: '# of Native Speakers',
data: $.map(nativeLanguages, function(n) {
console.log(n)
return n.count
}),
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
},
responsive: false,
maintainAspectRatio: true
}
});
})
});
}