Push Objects into an array in Jquery - javascript

I'm trying to fill an array with objects, but the array is not filling properly. The last value is set in all positions of the array. Here's the code:
var matrixprice = 5;
var qualifiedDate = '2019-10-01';
var today = new Date();
var qDate = new Date(qualifiedDate);
var nextDay = qDate;
var myObject = new Object();
var myArray = [];
var dailybonus = matrixprice * 0.03;
var full_bonus = matrixprice * 2;
var i = 0;
while (i <= full_bonus) {
nextDay.setDate(nextDay.getDate() + 1);
i += dailybonus;
myObject.title = '$' + i;
myObject.start = nextDay;
myArray.push(myObject);
}
var myString = JSON.stringify(myArray);
console.log(myString);
The array Im getting is filled with only 1 value in all positions it looks like this:
[{"title":"$100.5","start":"2020-01-03T18:50:23.000Z"}, {"title":"$100.5","start":"2020-01-03T18:50:23.000Z"},{"title":"$100.5","start":"2020-01-03T18:50:23.000Z"},{"title":"$100.5","start":"2020-01-03T18:50:23.000Z"},{"title":"$100.5","start":"2020-01-03T18:50:23.000Z"},{"title":"$100.5","start":"2020-01-03T18:50:23.000Z"}]
Thank you in advance!

Update your while loop to push a new object:
while(i <= full_bonus){
nextDay.setDate(nextDay.getDate()+1);
i += dailybonus;
myArray.push({title: '$'+i, start: new Date(nextDay)});
}
Here's the full, working example:
var matrixprice = 5;
var qualifiedDate = '2019-10-01';
var today = new Date();
var qDate = new Date(qualifiedDate);
var nextDay = qDate;
var myArray = [];
var dailybonus = matrixprice * 0.03;
var full_bonus = matrixprice * 2;
var i = 0;
while(i <= full_bonus){
nextDay.setDate(nextDay.getDate()+1);
i += dailybonus;
myArray.push({title: '$'+i, start: new Date(nextDay)});
}
var myString = JSON.stringify(myArray);
console.log(myString);

Related

How to combine arrays according indexes in javascript?

I have two 2d arrays:
var ar1 = [];
var ar1[0] = [];
var ar1[0][0] = 1;
var ar1[0][1] = 2;
var ar1[1] = [];
var ar1[1][0] = 3;
var ar1[1][1] = 4;
var ar2 = [];
var ar2[0] = [];
var ar2[0][3] = 5;
var ar2[0][4] = 6;
var ar2[1] = [];
var ar2[1][5] = 7;
var ar2[1][6] = 8;
How can I get the combined array that will look like:
var ar1[0][0] = 1;
var ar1[0][1] = 2;
var ar1[1][0] = 3;
var ar1[1][1] = 4;
var ar1[0][3] = 5;
var ar1[0][4] = 6;
var ar1[1][5] = 7;
var ar1[1][6] = 8;
I tried:
ar1.push(ar2);
but this puts whole ar2 to the first empty row of ar1.
One possibility is to forEach over the second array, and Object.assign each subarray onto the appropriate index in the first:
var ar1 = [];
ar1[0] = [];
ar1[0][0] = 1;
ar1[0][1] = 2;
ar1[1] = [];
ar1[1][0] = 3;
ar1[1][1] = 4;
var ar2 = [];
ar2[0] = [];
ar2[0][3] = 5;
ar2[0][4] = 6;
ar2[1] = [];
ar2[1][5] = 7;
ar2[1][6] = 8;
ar2.forEach((subarr2, i) => {
Object.assign(ar1[i], subarr2);
});
console.log(ar1);
Do note that var should only be used when declaring a new variable name for the first time - when assigning to an existing variable, omit it. (Also, sparse arrays are rarely a good idea)
You could iterate the second array and assign all values to the first array. For not given array in the second level take an array as default.
var ar1 = [],
ar2 = [];
ar1[0] = [];
ar1[0][0] = 1;
ar1[0][1] = 2;
ar1[1] = [];
ar1[1][0] = 3;
ar1[1][1] = 4;
ar2[0] = [];
ar2[0][3] = 5;
ar2[0][4] = 6;
ar2[1] = [];
ar2[1][5] = 7;
ar2[1][6] = 8;
ar2.forEach((a, i) => {
ar1[i] = ar1[i] || [];
a.forEach((v, j) => ar1[i][j] = v);
});
console.log(ar1);

add elements of two arrays - the best way

var a = "1:2:3:4";
var b = "0:1:5:2";
I want at the end:
var c = "1:3:8:6";
meaning, the numbers are summed by column.
my solution is:
var i, k;
var a_arr = a.split(':');
var b_arr = b.split(':');
for (i=0;i<a_arr.length;i++){
and here again another loop over b_arr
}
eeh ok, I dont have solution.. what is the cutest way to do this?
You could just map it and return the added values ?
var a = "1:2:3:4";
var b = "0:1:5:2";
var c = a.split(':').map(function(x, i) {
return (+x) + (+b.split(':')[i]);
}).join(':');
document.body.innerHTML = '<pre>' + c + '</pre>';
or splitting outside the map
var c = (function(y) {
return a.split(':').map(function(x, i) {
return (+x) + (+y[i]);
}).join(':')
})(b.split(':'));
Building on my comment, you can use i to index both the arrays:
var i, k;
var a_arr = a.split(':');
var b_arr = b.split(':');
var c_arr = [];
for (i=0;i<a_arr.length;i++){
c_arr.push(parseInt(a_arr[i], 10) + parseInt(b_arr[i], 10));
}
//And use join to get the final result
var c = c_arr.join(":");
You can use index i to add the simply use join()
var a = "1:2:3:4";
var b = "0:1:5:2";
var c = [];
var i, k;
var a_arr = a.split(':');
var b_arr = b.split(':');
for (i=0;i<a_arr.length;i++){
c[i] = parseInt(a_arr[i], 10) + parseInt(b_arr[i], 10); //Add using index
}
console.log(c.join(':')); //Use Join
http://jsfiddle.net/fLavfcjz/1/
Use .map() and don't forget parseInt() otherwise the numbers will considered as strings.
var a = "1:2:3:4";
var b = "0:1:5:2";
var arrayA = a.split(':');
var arrayB = b.split(':');
var combinedArr = arrayA.map(function (v, i) {
return parseInt(v,10) + parseInt(arrayB[i],10); // or return (+v) + (+arrayB[i]);
});
console.log(combinedArr.join(':')); //1:3:8:6
Try this
var a = "1:2:3:4";
var b = "0:1:5:2";
var a_arr = a.split(':');
var b_arr = b.split(':');
var c_arr = [];
for (i in a_arr) {
var to_add = 0;
if (b_arr[i] != undefined) to_add = b_arr[i];
c_arr[i] = a_arr[i] + to_add;
}
You don't need a second loop. The resulting array of the following snippet will have the length of the shorter input array.
var a = '1:2:3:4'
var b = '0:1:5:2'
var aArray = a.split(':')
var bArray = b.split(':')
var result = []
for (
var i = 0, aLength = aArray.length, bLength = bArray.length;
i < aLength && i < bLength;
i++
) {
result.push(Number(a[i]) + Number(b[i]))
}
result = result.join(':')
console.log(result)

Change Array Formatting

How to change this Javascript array format:
var sample_data = ["af","16.63","al","11.58","dz","158.97"];
to this object format:
var sample_data = {"af":"16.63","al":"11.58","dz":"158.97"};
Could use Array.shift to do it too. No idea how it compares to other methods speed wise.
var sample_data = ["af","16.63","al","11.58","dz","158.97"]; // source
var data = sample_data.slice(); // clone the data
sample_data = {};
while (data.length > 1) {
sample_data[data.shift()] = data.shift() || null;
}
var d = {}; // a temporary object
for (var i = 0; i < sample_data.length; i += 2) {
// iterate over sample_data with a step width of 2
// and set the the data in the temp. object
d[sample_data[i]] = sample_data[i+1];
}
sample_data = d;
the code for it will look like this
var sample_data = ["af","16.63","al","11.58","dz","158.97"];
var tmp = sample_data;
sample_data = {};
for (var i = 0; i < tmp.length / 2; i++)
sample_data[tmp[i * 2]] = tmp[i * 2 + 1];
EDIT
Keep in mind.
var arr = []; // This is an array
var obj = {}; // This is an object! Not array.

Find missing element by comparing 2 2D-Arrays in Javascript

A few days ago I posted a thread asking on how to find the missing element when passing a method 2 JS arrays. As you can see here. I've been trying to figure out now how to modify the method so that instead of passing it 2 Arrays you pass it 2 2D-Arrays... Having some trouble though:
/*var sml = new Array();
sml[0] = new Array("dean","22");
sml[1] = new Array("james","31");
sml[2] = new Array("ludwig","35");
var lrg = new Array();
lrg[0] = new Array("dean","22");
lrg[1] = new Array("james","31");
lrg[2] = new Array("ludwig","35");
lrg[3] = new Array("kevin","23");
lrg[4] = new Array("elton","40");*/
var sml = new Array();
sml[0] = "dean";
sml[1] = "james";
sml[2] = "ludwig";
var lrg = new Array();
lrg[0] = "dean";
lrg[1] = "james";
lrg[2] = "ludwig";
lrg[3] = "kevin";
lrg[4] = "elton";
var deselected = findDeselectedItem(sml, lrg);
alert("Deselected Items: " + deselected[0]+", "+ deselected[1]);
// -------------------------------------------------------------- //
function findDeselectedItem(CurrentArray, PreviousArray) {
var CurrentArrSize = CurrentArray.length;
var PreviousArrSize = PreviousArray.length;
var deselectedItems = new Array();
// loop through previous array
for (var j = 0; j < PreviousArrSize; j++) {
// look for same thing in new array
if (CurrentArray.indexOf(PreviousArray[j]) == -1)
deselectedItems.push(PreviousArray[j]);
}
if (deselectedItems.length != 0) {
return deselectedItems;
} else {
return null;
}
}​
Now if you run the above code it works perfectly, but if you go and uncomment the variable declarations on top that that pushes arrays ontop of the array, and then comment out the simple strings that get pushed on top of the array, it doesn't work as well... For instance:
var sml = new Array();
sml[0] = new Array("dean","22");
sml[1] = new Array("james","31");
sml[2] = new Array("ludwig","35");
var lrg = new Array();
lrg[0] = new Array("dean","22");
lrg[1] = new Array("james","31");
lrg[2] = new Array("ludwig","35");
lrg[3] = new Array("kevin","23");
lrg[4] = new Array("elton","40");
/*var sml = new Array();
sml[0] = "dean";
sml[1] = "james";
sml[2] = "ludwig";
var lrg = new Array();
lrg[0] = "dean";
lrg[1] = "james";
lrg[2] = "ludwig";
lrg[3] = "kevin";
lrg[4] = "elton";*/
var deselected = findDeselectedItem(sml, lrg);
alert("Deselected Items: " + deselected[0]+", "+ deselected[1]);
// -------------------------------------------------------------- //
function findDeselectedItem(CurrentArray, PreviousArray) {
var CurrentArrSize = CurrentArray.length;
var PreviousArrSize = PreviousArray.length;
var deselectedItems = new Array();
// loop through previous array
for (var j = 0; j < PreviousArrSize; j++) {
// look for same thing in new array
if (CurrentArray.indexOf(PreviousArray[j][0]) == -1)
deselectedItems.push(PreviousArray[j][0]);
}
if (deselectedItems.length != 0) {
return deselectedItems;
} else {
return null;
}
}​
The method returns 2 completely wrong values. PS - I'm not interested in the "numbers" just yet, just the "names" for now...
Your CurrentArray is 2-dimensional and indexOf compares Arrays but not first elements of that Arrays. So you need to use:
for ( var i = 0; i < CurrentArray.length; ++i){
if (CurrentArray[i][0] == PreviousArray[j][0]){
deselectedItems.push(PreviousArray[j][0]);
break;
}
}
Instead of
if (CurrentArray.indexOf(PreviousArray[j][0]) == -1)
deselectedItems.push(PreviousArray[j][0]);
You could also rearrange the array like this:
var sml = {};
sml["dean"] = 22;
sml["james"] = 31;
sml["ludwig"] = 35;
var lrg = {};
lrg["dean"] = 22;
lrg["james"] = 31;
lrg["ludwig"] = 35;
lrg["kevin"] = 23;
lrg["elton"] = 40;
and use:
function findDeselectedItem(c,p){
ret=[];
for (var i in p){
if (p.hasOwnProperty(i)){
if ('undefined'===typeof c[i]) {
ret.push(i);
}
}
}
return ret;
}
alert(findDeselectedItem(sml, lrg));
Demo: http://jsfiddle.net/LsrCj/
indexOf function will check object equality in this case; to make it return something else than -1 you've to pass same 2D array instances to sml and lrg.
new Array("dean","22") === new Array("dean","22") //false
Keep the same instances (e.g. http://jsfiddle.net/3TQYz/) in both arrays or use your own indexOf test that would recursively check values of the array to make your case working.

Can't add to javascript array in loop

I'm having some issues with the following code:
var tmpArray = new Array();
for(var n in fnlArray){
if(fnlArray[n] == largest.val){
alert(fnlArray[n] +"-"+ largest.val);
tmpArray[n] = fnlArray[n];
}
}
fnlArray contents is:
fnlArray['result1'] = 1;
fnlArray['result2'] = 2;
fnlArray['result3'] = 2;
fnlArray['result4'] = 2;
and largest.val = 2;
The issue I'm having is the alert gets fired so I would expect to end up with tmpArray with the following:
tmpArray['result2'] = 2;
tmpArray['result3'] = 2;
tmpArray['result4'] = 2;
But the array (tmpArray) is always empty. Is this an issue with adding items to the array dynamically within a loop?
var tmpArray = new Array(); should be:
var tmpArray = {};
Your tmpArray object is not a index array, so you have to use object literals.
var tmpArray = {};
for(var n in fnlArray){
if(fnlArray[n] == largest.val){
tmpArray[n] = fnlArray[n];
}
}
alert(JSON.stringify(tmpArray)); //Prints: {"result2":2,"result3":2,"result4":2}
Demo: http://jsfiddle.net/QhFGF/

Categories