Sorting csv according to particular column - javascript

Hi I am exporting data to csv file using javascript. I need to sort the data according to specific column index.
Code:
$.each(exportArray, function (index, value) {
csvData.push(x[index] + "," + y[index] + "," + d[index] + "," + z[index] + ","+ a[index] + "," + e[index] + "," + b[index] + "," + c[index]);
});
csvData.sort();
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(output);
$(this)
.attr({
'download': filename,
'href': csvData,
'target': '_blank'
});
E.g.: csvData.sort() is sorting data acoording to first column as default. I want to have it sorted according to the third column i.e.. by d[index].
I tried this csvData.sort(sort_by(d[index])); and it is not working.
I have one more issue . Since I am exporting the data to csv. Now in d[index] from the server if I have three values like d[index]="cat,dog,bat" . It is getting displayed in 3 adjacent columns. I want it in the same column. Can I change the delimiter to something else from comma.
Code:
csvData.push(x[index] + "," + y[index] + "," + d[index] + "," + z[index] + ","+ a[index] + "," + e[index] + "," + b[index] + "," + c[index]);

You need to sort the data before you write it to the CSV. This is more easily done if the data is in an array of objects instead of spread out in one array per property. To achive this you can either just put the data in objects when it is created or read, or you can convert it with a snippet like this:
var count = x.length;
var objects = new Array(count);
for(i=0; i++; i<count) {
objects[i] = {
x: x[i],
y: y[i],
d: d[i],
z: z[i],
a: a[i],
e: e[i],
b: b[i],
c: c[i],
};
}
Then you can easily sort the data, for example by the x property, with this code:
function compare(a, b) {
if (a.x < b.x) return -1;
if (a.x > b.x) return 1;
return 0;
}
objects.sort(compare);
Then you will get the arrays sorted, and can access individual properties with for instance objects[i].x.

You have to write a custom compare function
// The following function is used to sort on the basis of the third element
function compareByThird(a, b) {
var aArr = a.split(',');
var bArr = b.split(',');
return aArr[2] - bArr[2];
}
csvData.sort(compareByThird);
It works if the third column is a numeric value.
If not (for example for strings) it necessary to use the following code:
// The following function is used to sort on the basis of the third element
function compareByThird(a, b) {
var aArr = a.split(',');
var bArr = b.split(',');
if (aArr[2] < bArr[2]) {
return -1;
} else if (aArr[2] > bArr[2] {
return 1;
} else {
return 0;
}
}

Related

I want to generate a random color using rgb in JavaScript but it's not working

this is my code
document.querySelector(".btn").addEventListener("click", colorChange)
function colorChange() {
var arr = []
for (let i = 0;i<3;i++) {
var random = Math.floor(Math.random() * 255)
arr.push(random)
}
document.querySelector("body").style.backgroundColor = "rgb(arr[0], arr[1], arr[2])"
}
first I added an event listener to a button with the class "btn" and then I declared a function and declared an empty array in it called "arr" and then I used a for loop and declared a variable called random to generate three random numbers push
them to the empty array
document.querySelector("body").style.backgroundColor = "rgb(arr[0], arr[1], arr[2])"
Currently, you are passing the static string value rgb(arr[0], arr[1], arr[2]).
Solution:
document.querySelector("body").style.backgroundColor = `rgb(${arr[0]}, ${arr[1]}, ${arr[2]})`
You don't access the array fields. You only wrote a string. Do it this way.
document.querySelector("body").style.backgroundColor = "rgb(" + arr[0] + "," + arr[1] + "," + arr[2] +")"
Return with your function the rgb string that you need created with random values, like bellow for exemple.
Then just use it where ever you want to use it, like in your style.backgroundColor if you wish.
function random_rgb() {
var o = Math.round, r = Math.random, s = 255;
return 'rgb(' + o(r()*s) + ',' + o(r()*s) + ',' + o(r()*s) + ')';
}
var color = random_rgb();
document.querySelector("body").style.backgroundColor = color
console.log(color)

Pushing an array into another array - nested

I am creating a store. The way it works is that when I click 'add to cart', I run a function which gets the id of the button. From that id, you can work out the name of the product, get the cost, quantity etc. For simplicity, this is the funciton code:
function getID(a){
var id = a.substring(0, a.length - 4);
var id_quant = document.getElementById(id + '_val').value;
var id_name = document.getElementById(id + '_nme').innerHTML;
console.log(id + " " + id_quant + " " + id_name);
}
You may notice that I remove the last 4 digits from this.id, this is because when I run the PHP to echo all the results, i make the button_id equal to the uid from the database, concatenated with _btn.
What I would then like to do is to push this into an array, or use JSON.
What I am imagining is a nest array like : array[uid][cost], array[uid][name]. I'm just not sure how to do this.
It should be noted that in the function, a is actually this.id:
<button id='1_btn' onclick='getID(this.id)'></button>
I have declared an array above the function, var array = [].
Any help on how to push a nest would be great.
What I would then like to do is to push this into an array, or use
JSON.
You need to use an object
var obj = {};
and set values in this obj from the function as
function getID(a){
var id = a.substring(0, a.length - 4);
var id_quant = document.getElementById(id + '_val').value;
var id_name = document.getElementById(id + '_nme').innerHTML;
obj[ id ] = { quantity : id_quant, name : id_name }; //observe this line
console.log(id + " " + id_quant + " " + id_name);
}
instead of array you should have an object.
var bucket = {};
bucket[someuid] = {
"cost": 500,
"name": "Some Item"
}
Now you can access this simply by,
console.log(bucket[someuid]);
Iterating then is simple
for (item in bucket){ console.log(item['name'], item['cost']) }

Sorting arrays by largest to smallest numbers with Ajax and Jquery

I need to create an Ajax/Jquery call that will sort an array(https://fcctop100.herokuapp.com/api/fccusers/top/alltime) from smallest to largest using the "alltime" var in the array.
$("#start").click(function(){
function SortByalltime(a, b) {
var aNum = a.alltime.sort();
var bNum = b.alltime.sort();
return ((aNum < bNum) ? -1 : ((aNum > bNum) ? 1 : 0));
}
$.get("https://fcctop100.herokuapp.com/api/fccusers/top/recent", function(data) {
//here we run the function to sort the array of data before transforming it to table
data.sort(SortByalltime);
var table = '<table>'
for (var i = 0; i < data.length; i++) {
table += '<tr><td>' + data[i].alltime + '</td><td><img width=20 height=20 src="' + data[i].img + '"></td><td>' + data[i].lastUpdate + '</td><td>' + data[i].recent + '</td><td>' + data[i].username + '</td></tr>';
}
$('body').append(table);
});
});
Here is my current call, I would appreciate any help.
alltime is an integer rather than an array
So simply replace
var aNum = a.alltime.sort();
var bNum = b.alltime.sort();
with
var aNum = a.alltime;
var bNum = b.alltime;
For smallest to largest
function SortByalltime(a, b) {
return (a.alltime - b.alltime);
}
For largest to smallest
function SortByalltime(a, b) {
return (b.alltime - a.alltime);
}
Use the property alltime for sorting.
function SortByalltime(a, b) {
return b.alltime - a.alltime;
}

Need help accessing JSON array object

Objective: This code collects an array JSONAPIS and passes the APIS into a $.each() loop. Then JSON data field are evaluated in if statements and used to calculate precip. How do I access the JSONAPIS from the obj.
Main issue: obj.daily.data.length is undefined on the daily array member. The obj should contain one of the API calls and the JSON dataset to use. Instead it contains keyword like abort, always, promise which I am not familiar how to use. What would access the result JSON object property?
var listAPIs = "";
var darkForecastAPI = [];
var result = [];
var JSONAPIS = [];
$.each(numDaysAPITimes, function(a, time) {
var darkForecastAPI = /*"http://api.wunderground.com/api/" + currentAPIKey + "/history_" + time + "/q/" + state + "/" + city +".json?callback=?"; */
"http://api.forecast.io/forecast/" + currentAPIKey + "/" + city + time + "?callback=?";
//https://api.forecast.io/forecast/APIKEY/LATITUDE,LONGITUDE,TIME
JSONAPIS.push($.getJSON(darkForecastAPI, {
tags: "WxAPI[" + i + "]", //Is this tag the name of each JSON page? I tried to index it incase this is how to refer to the JSON formatted code from the APIs.
tagmode: "any",
format: "json"
}));
});
$.when.apply($, JSONAPIS).done(function(result) { /*no log simply an array */
var eachPrecipSum = 0.0;
var totalPrecipSinceDate = 0.0;
alert(result);
$.each(result, function(d, obj) {
console.log(obj);
for (var c = 0; c <= obj.daily.data.length - 1; c++) {
if (obj.daily.data[c].precipIntensity >= 0.0000 && obj.daily.data[c].precipType == "rain") /*Number(result.history.dailysummary.precipm, result.history.dailysummary.rain*/ {
eachPrecipSum = result[d].daily.data[c].precipIntensity;
totalPrecipSinceDate = eachPrecipSum + totalPrecipSinceDate; ///Write mean precip
alert(Math.round(eachPrecipSum * 10000) / 10000);
$("body").append("p").text("There has been as least a total of " + Math.round(totalPrecipSinceDate * 10000) / 10000 + " inches per hour of rain at the location in the last " + userDataDatePick + " days")
} else if (obj.daily.data[c].precipIntensity >= 0.0000 && obj.daily.data[c].precipType != "rain") {
alert("There is was no rain on ____" /*+ result.history.dailysummary.mon + "/" + result.history.dailysummary.mday + "/" + result.history.dailysummary.year*/ );
}
}
});
});
numDaysAPITimes = 0;
}
$.when doesn't take array as input
Since you are passing an array that isn't itself a promise it is likely firing immediately and therefore ahead of all the ajax calls completing
Need to change to
$.when.apply(null, JSONAPIS).done...

How to create an array of variables from an array in Javascript

I have a variable called "information" which creates a multi-dimensional array. For each row in the array, I want to return a variable whose name is the first value in the array. In other words, given the 'information' array below, I'd want the following output:
var lunalovegood = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i] [1] + '!'; //Luna Lovegood is a Ravenclaw!;
var dracomalfoy = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i] [1] + '!'; //Draco Malfoy is a Slythering!;;
var hermionegranger = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i] [1] + '!'; //Hermione Granger is a Gryffindor!;;
In other words, I want to be able to work with each of the elements in the 'information' array to create some markup. I already know how to get the information I need given the information array, but as you can see below I'd have to declare separate variables for each of the names.
for (var i = 0; i < information.length; i++) {
var htmlString = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i] [1] + '!'; //Luna Lovegood is a Ravenclaw!
$('div').html(htmlString);
} //end for loop
var information = [
['lunalovegood', 'Ravenclaw', 'Luna', 'Lovegood', '(chaser)', 'lovegood.jpg', 4]
['dracomalfoy', 'Slytherin', 'Draco', 'Malfoy', '(seeker)', 'malfoy.jpg', 2],
['hermionegranger', 'Gryffindor', 'Hermione', 'Granger', '(none)', 'granger.jpg', 3],
];
The javascript below creates three variables called 'lunalovegood', 'dracomalfoy', and 'hermionegrange', but it's the long way of creating variables. How do I create these variables, one for each row in the array, by looping through the 0th indexed element in the 'information' array?
var myVariables = {}
,varNames = ["lunalovegood","dracomalfoy","hermionegranger"];
for (var i=0;i<varNames.length;i+=1){
myVariables[varNames[i]] = 0;
console.log(lunalovegood);
}
Your current approach just needs a most minor tweak to not require the second array.
var students = {}, i;
for (i = 0; i < information.length; ++i)
students[information[i][0]] = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i][1] + '!';
Now the key is set by taking the first item of the Array. You would then do the following for your text,
students['lunalovegood']; // "Luna Lovegood is a Ravenclaw!"
You're also missing a , in your information literal.
This should help you:
Every variable in the global scope can be accessed as a string property of the window object
var myvariable = 4;
alert(window["myvariable"]); // will alert 4
window["newvariable"] = 6;
alert(newvariable); // will alert 6
I agree with Bergi. Variables should represent a fixed finite set of members defined by code; data (as in the contents of a list) should generally not introduce new variables.
As such, here is the approach I would recommend (note that I've added a bit more than the "minimum required"; good luck!):
// Using a function makes it easy to change details and avoid leaking
// variables accidentally.
function loadWizards(information) {
var wizards = [];
for (var i = 0; i < information.length; i++) {
var info = information[i];
var name = info[0];
// Mapping to named properties means we can forget about indices!
wizards[name] = { // <- use Name to map to our Wizard object
house: info[1],
// ..
image: info[7]
};
}
return wizards;
}
// I have no idea if they are wizards, but give variables useful names.
// 'information' is too generic.
var wizards = loadWizards(information);
// Then later on, use it as:
alert("Hello " + wizards['hermionegranger'].name + "!")
// ^-- property access by Name
var formattedInfo = {};
$.each(information, function (i, v) {
formattedInfo[v[0]] = v[2] + ' ' + v[3] + ' is a ' + v[1];
});
there is a missing comma at the end of the 1st line of your definition of information.
BTW, I like Harry Potter very much.

Categories

Resources