Are js array indexes set if not defined - javascript

I am working on a script in which i need some data based on a lot of timestamps.
Below is just an example
var timestampData1 = [1555486016,1555486017,1555486018...];
var timestampData2 = [1555486016,1555486017,1555486018...];
var data = [];
data[1] = [];
$.each(timestampData1,function(index,value) {
data[1][value] = 1;
});
data[2] = [];
$.each(timestampData2,function(index,value) {
data[2][value] = 1;
});
console.log(data);
The example above will output the following in the console
However if i examine the data in the console, i see a lot of empty sets counting from 0 up to the very last timestamp
So my question is:
Will javascript set all of these indexes, or is it simply an indication in the console?
If not, i guess that it is very bad for performance, doing it like above ?

Yes your assumption is correct. If you use objects which have key/value pairs whis won't be a problem, however you will you array methods like push and filter.
Example:
var timestampData1 = [1555486016,1555486017,1555486018...];
var timestampData2 = [1555486016,1555486017,1555486018...];
var data = [];
//Make data[1] an object not array
data[1] = {};
$.each(timestampData1,function(index,value) {
data[1][value] = 1;
});
//Make data[1] an object not array
data[2] = {};
$.each(timestampData2,function(index,value) {
data[2][value] = 1;
});
console.log(data);
Output:

Related

objects not properly pushed in array

The code below is supposed to decompose a json object sent from Postman into smaller objects that will be stored in a array. The problem is that if I console.log the result, I do see each and every objects decomposed as expected but the array.push method only push the last element of the inner array :
app.post('/commande',async(req,res)=>{
if( await authentification(req.query.login, req.query.pass)){
var data = req.body.data; // array containing json object to be posted
var dataLength = data.length;
var bigObj= []; //array to store objects
for (var i = 0; i<dataLength; i++) {
var orderLines = data[i].orderLines;//array of orders
var info ={};// object unit
info.CptClient = data[i].clientAccount;
info.customerOrderNumber= data[i].customerOrderNumber;
info.orderLabel = data[i].orderLabel;
var shipTo = data[i].shipTo;
info.recepientName = shipTo.recepientName;
info.contactName = shipTo.contactName;
info.ad1 = shipTo.ad1;
info.ad2 = shipTo.ad2;
info.ad3 = shipTo.ad3;
info.postalCode = shipTo.postalCode;
//"etc..."
//
for (var j = 0; j<orderLines.length;j++) {
info.itemRef = orderLines[j].itemRef;
info.itemQty = orderLines[j].itemQty;
info.unitPrice = orderLines[j].unitPrice;
console.log(info);//displays unique orderLabel : ABC01 ABC02 ABC03 XYZ01 XYZ02 XYZ03
bigObj.push(info); // stores only last of each type : ABC03 ABC03 ABC03 XYZ03 XYZ03 XYZ03
}
}
res.json(bigObj)
}else {
res.send("not authorized");
}
})
As explained in the comments, the console.log displays the right information as the objects are being created but the push method somehow would only push the last element of the orderLines array. Is there somebody to explain this phenomenon? Any idea? Thank you.

Get payload from String

I have this String:
['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
I want to get the keys 'TEST1-560' which is always fist and "car" value.
Do you know how I can implement this?
This is a very, very scuffed code, but it should work for your purpose if you have a string and you want to go through it. This can definitely be shortened and optimized, but assuming you have the same structure it will be fine.:
// Your data
var z = `['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']`;
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1,dividedVar[ind].split(":")[1].split("}")[0].length-1);
console.log(car)
}
}
console.log(testName);
output:
BLUE
TEST1-560
In a real application, you don't need to log the results, you can simply use the variables testName,car. You can also put this in a function if you want to handle many data, e.g.:
function parseData(z) {
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1, dividedVar[ind].split(":")[1].split("}")[0].length - 1);
}
}
return [testName, car]
}
This will return the variables values in an array you can use
const arr = ['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
const testValue = arr[0];
const carValue = JSON.parse(arr[1]).data[0].car;
console.log(testValue);
console.log('-----------');
console.log(carValue);
If your structure is always the same, your data can be extracted like above.

jQuery/JavaScript - Converting CSV to Array

I am trying to to convert a CSV file into a javascript array.
Here is my code:
var segments = {
'Segment_1':'inves_cast',
'Segment_2':'foreged_prod',
'Segment_3':'air_prod',
'Segment_5':'worldwide',
'Segment_6':'structurals'
};
var divisions = {
'Division_1':'structurals',
'Division_2':'airfoils',
'Division_3':'wyman',
'Division_4':'energy',
'Division_5':'fasteners',
'Division_6':'struc_comp',
'Division_7':'mech_hard',
'Division_8':'engine_prod',
'Division_9':'corp',
'Division_10':'aero',
'Division_11':'timet',
'Division_12':'',
'Division_13':'spec_metals',
};
var csv = $.get('/path/to/locations.csv');
console.log(csv);
var locationArray = transformLocationData(csv);
function transformLocationData(obj) {
var lineArray = [];
if(obj && obj.data) {
var text = (data.responseText);
lines = text.split('\n');
for(var line in lines) {
var lineTokens = line.split(',');
lineArray = [
lineTokens[0],
lineTokens[1],
lineTokens[3],
lineTokens[4],
lineTokens[5],
lineTokens[6],
lineTokens[11],
lineTokens[12],
lineTokens[13],
lineTokens[14],
lineTokens[15],
segments['Segment_' + lineTokens[8]],
divisions['Division_' + lineTokens[9]]
];
}
}
console.log(lineArray);
}
So what I am trying to do is us AJAX to get the csv file and then split the "responseText" first by line and Second loop through those lines and split it up by commas and then create an array based on those line numbers.
Here is a picture of the data I am getting back from the AJAX call:
With the last console log ( console.log(lineArray); ) it returns an empty array or really it just returns the data the is in var lineArray = []; which is empty if I populate it with data var lineArray = ["Lexus", "Audi", "BMW"]; It will return that array.
Here is a plunker with all the code: https://plnkr.co/edit/CoZGfr6S9R5LDqR1drzq
I know I am doing something wrong but cant seem to get it. I'm not familiar with doing this kind of thing so any help would be greatly appreciated.
You are replacing lineArray with a new array every time, and you're only logging the array at the end of the loop. Perhaps the CSV has an empty line at the end.
If you're wanting an array of arrays, do this instead:
var lineArray = [];
if(obj && obj.data) {
var text = (data.responseText);
lines = text.split('\n');
for(line in lines) {
var lineTokens = line.split(',');
lineArray.push([
lineTokens[0],
lineTokens[1],
lineTokens[3],
lineTokens[4],
lineTokens[5],
lineTokens[6],
lineTokens[11],
lineTokens[12],
lineTokens[13],
lineTokens[14],
lineTokens[15],
segments['Segment_' + lineTokens[8]],
divisions['Division_' + lineTokens[9]]
]);
}
}
console.log(lineArray);
Update:
In addition, you're not handling the results from the Ajax request properly. This line:
var csv = $.get('/path/to/locations.csv');
...does not return the CSV. Rather, it returns a Promise (sort of...). So you cannot parse csv like that. Rather, wait for the results. Change your code to:
$.get('/path/to/locations.csv').then(function (csv) {
var locationArray = transformLocationData(csv);
}, function (err) {
// Handle errors
});
As #vlaz alluded to, you'll also want to change your loop from for..in to a regular for loop:
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
// ...
}

Creating 2d array of objects in javascript with string keys

I'm trying to create a summary report for a order based on products in the order
However my summary array is always empty.
var summary = [];
_.each(this.products, function(product,counter) {
var invoice = {};
invoice.total = 0;
invoice.dealer_discount = 0;
invoice.program_discount = 0;
invoice.adjusted_total = 0;
_.each(product.materials, function(material) {
_.each(material.variants, function(variant) {
var difference = 0;
invoice.total = parseFloat(invoice.total + variant.price.msrp);
if(variant.price.discount_type === 'dealer') {
difference = parseFloat(variant.price.msrp - variant.price.discount_price);
invoice.dealer_discount = parseFloat(invoice.dealer_discount + difference);
} else {
difference = parseFloat(variant.price.msrp - variant.price.discount_price);
invoice.program_discount = parseFloat(invoice.program_discount + difference);
}
});
});
// This never seems to get populated?
// If I set the array key to counter like summary[counter] it works fine but I need:
summary[product.fulfilled_by] = invoice;
});
It is probably something simple that I'm doing wrong.
Any help is appreicated.
Just changing the first line will solve your problem
var summary = {}; // Object
An Object store items in key : value fashion, while an Array will just contain value which can be accessed by an index which is numeric and hence worked when you put summary[counter].

How to separate the values from two dimension array in js?

jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
$('#div1').append(msgid);
$('#div2').append(rspid);
});
Let's say the value of newitems is [["320","23"],["310","26"]]
I want to assign "320" and "310" to var msgid.
I want to assign "23" and "26" to var rspid.
How to do that?
I tried to display newitems and the output is "Array". I tried to display newitems[0] and the output is blank.
If I redeclare var newitems = [["320","23"],["310","26"]]; it works. So I guess the variable newitems from jQuery.get is something wrong. Is it I cannot pass the array from other page to current page through jQuery directly?
Regarding the array on other page, if echo json_encode($Arraytest); the output is [["320","23"],["310","26"]] but if echo $Arraytest; the output is Array. How do I pass the array from other page to currently page by jQuery.get?
I don't totally understand the question but I'm going to assume you want the values in an array, as two values can't be stored in one (scalar) variable simultaneously.
jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
var msgid = [],
rspid = [];
for( i = 0 ; i < newitems.length ; i++){
msgid[msgid.length] = newitems[i][0];
rspid[rspid.length] = newitems[i][1];
}
//msgid now contains ["320","310"]
//rspid now contains ["23","26"]
});
Bear in mind those are in the function scope. If you want to use them outside of that scope instantiate them outside. see: closure
You can use pluck from underscore.js: http://documentcloud.github.com/underscore/#pluck
var msgid = _(newitems).pluck(0)
var rspid = _(newitems).pluck(1)
Try this:
function getArrayDimension(arr, dim) {
var res = [];
for(var i = 0; i < arr.length; i++) {
res.push(arr[i][dim]);
}
return res;
}
var newitems = [["320","23"],["310","26"]];
var msgid = getArrayDimension(newitems, 0);
var rspid = getArrayDimension(newitems, 1);
msgid and rspid are arrays holding the 'nth' dimention.
Tnx

Categories