javascript push duplicating values - javascript

I have a single input row that needs to be expanded to create multiple rows, with 6 fields being repeated on each row, and one unique field added to each row. The unique fields are stored in arrparentjobs array, and I know that they have unique values.
When the code runs, the resulting rows all contain the exact same data, which happens to be the values of the last items being pushed.
What am I doing wrong here?
Thanks much,
Joe
var dataRowsOutput = [];
arrVolDataOutput.playerid = volDataRow.playerId;
arrVolDataOutput.timestamp = volDataRow.timestamp;
arrVolDataOutput.playername = volDataRow.playerName;
arrVolDataOutput.parentname = volDataRow.parent1Name;
arrVolDataOutput.parentphone = volDataRow.parent1Phone;
arrVolDataOutput.parentemail = volDataRow.parent1Email;
for (var j = 0; j < arrparentjobs.length; ++j) {
arrVolDataOutput.parentjob = arrparentjobs[j];
dataRowsOutput.push(arrVolDataOutput);
continue;
}

the resulting rows all contain the exact same data
Yes they do and they do because push pushes a reference – not a deep or even shallow copy – onto the array and you're simply changing the parentjob while pushing the exact same arrVolDataOutput object onto the array over and over again.
You need to create a new object on each iteration, something like this:
var dataRowsOutput = [];
for (var j = 0; j < arrparentjobs.length; ++j) {
dataRowsOutput.push({
parentjob: arrparentjobs[j],
playerid: volDataRow.playerId,
timestamp: volDataRow.timestamp,
playername: volDataRow.playerName,
parentname: volDataRow.parent1Name,
parentphone: volDataRow.parent1Phone,
parentemail: volDataRow.parent1Email
});
}
If there are other fields in your arrVolDataOutput then you'll need to include those in the object literal as well.

Related

How to push values from array into row?

How to push values from array into row in exceljs?
i try with this:
const columns = ['string', 'string2', 'string3'];
for(let i=0; i < columns.length; i++) {
workSheet.getRow(1).values = [dto.columns[i]];
}
but this code add only one item from the columns list :/
have anybody any idea how to resolve this problem? I must add objects from array, I know that, i can do this:
workSheet.getRow(1).values = ['string','string2', 'string3'];
but this is not for me :(
thanks for any help
You are reassigning the value inside the for loop. So, you will always get the last item inside the values property. You can initialize the values as empty array before for loop and then try putting the item in the values.
const columns = ['string', 'string2', 'string3'];
workSheet.getRow(1).values = [];
for(let i=0; i < columns.length; i++) {
workSheet.getRow(1).values.push(dto.columns[i]);
}

Adding objects to Array of objects Javascritp

Probably this is an obvius question, but I'm pretty new on JS.
This is always inserting the same item repeated, it is changing the value of the last item inserted on the array when the object change the value, how can I avoid it and insert all the values that I¡m itereating?
self.user.userSociedadesAreasLink =[];
var userSociedadesAreasLink = {};
for(var i =0 ; i< self.selectedSociedades.length ; i++){
userSociedadesAreasLink.sociedad = self.selectedSociedades[i];
self.user.userSociedadesAreasLink.push(userSociedadesAreasLink);
}
You are using the same object every time to push into the array, only changing the property's value. You have to create a new object everytime to make it as a unique object.
self.user.userSociedadesAreasLink =[];
for(var i =0 ; i< self.selectedSociedades.length ; i++){
var userSociedadesAreasLink = {};
userSociedadesAreasLink.sociedad = self.selectedSociedades[i];
self.user.userSociedadesAreasLink.push(userSociedadesAreasLink);
}
This should solve the issue.
You could just push a new object literal each time. You could also just use a map operation for this.
self.user.userSociedadesAreasLink = self.selectedSociedades.map(s => ({sociedad: s}));

Unable to .empty() the appended elements

state.on('change', function(){
city.empty();
$.getJSON("pincodes.JSON", function(pincodes){
var key = state.val();
for (var j= 0; j < pincodes['address'].length; j++) {
if (pincodes['address'][j]['circlename'] == key) {
temp.push(pincodes['address'][j]['regionname']);
}
}
cities = $.unique(temp);
for (var k = 0; k < cities.length; k++) {
city.append('<option>' + cities[k] + '</option>');
}
});
});
In the above state = $('#state') , the above works fine fills the cities on select "state" . But the issue is when a new state is selected the previously filled cities are also there . Even though I tried .empty on every change() .
You don't empty your temp array. So, every time this function is called, you keep appending items to your temp array.
You simply need to add the following line in your code:
state.on('change', function() {
city.empty();
temp = []; // <---
$.getJSON("pincodes.JSON", function(pincodes) {
What about cities = $.unique(temp);, it won't work.
According to jQuery.unique() documentation, this function
Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.
So, it is not a correct usage. If you get non-unique values from your JSON, you will need to use another way to get distinct values. There is a good SO article on this topic.

Javascript multiple array push() differences

I have problem with pushing data. I want to prepare data (time,temperature,humidity) for plotting (Dygraphs). But when I´m filling variable data with this one code (see below) I don´t get graph.
for (var i = 0; i < time.length; i++){
var t = new Date (time[i]);
data.push(t);
for(var n = 0; n < 2; n++){
data.push([data_graph[n][i]]);
}
}
But when I leave one for-cycle and manually write nums of arrays (see below), It works and I get graph.
for (var i = 0; i < time.length; i++){
var t = new Date (time[i]);
data.push([t,data_graph[0][i],data_graph[1][i]]);
}
I got idea to use temporary variable, but also with no success.
for (var i = 0; i < time.length; i++){
var data_temporary = [];
var t = new Date (time[i]);
for(var n = 0; n < 2; n++){
data_temporary.push([data_graph[n][i]]);
}
data.push([t,data_temporary]);
}
So my question is...where could be a problem?
Thanks in advance for answers.
Yes, your three code snippets generate three different data structures:
[t, [datagraph…], [datagraph…], t, [datagraph…], [datagraph…], …]
[[t, datagraph…, datagraph…], [t, datagraph…, datagraph…], …]
[[t, [[datagraph…], [datagraph…]]], [t, [[datagraph…], [datagraph…]]], …]
Too often you pushed one-element-arrays, btw.
So if you want struc#2 generated by a loop, use
for (var i=0; i<time.length; i++) {
var t = new Date (time[i]);
var temp = [t]; // or temp=[]; temp.push(t);
for (var j=0; j<data_graph.length; j++) // or j<2 if that's certain
temp.push(data_graph[j][i]);
data.push(temp);
}
Each call to push() creates a new element in your data array. So, in your first example, you are passing 3 objects on each iteration of the outer for loop, and in the third example you are passing an object that consists of time and an array of two values. But the dygraph script apparently expects objects consisting of three elements, so your second example works.
The second (working) version creates a two dimension array with time.length elements in the first dimension each containing three elements [t, x, y], as required.
In the first version you are creating a one-dimensional array [t0, [x0], [y0], t1, [x1], [y1], ...].
Your third version doesn't work because whilst you correctly create time.length elements in the first dimension, the elements themselves are [t, [[x], [y]]], and not [t, x, y].

Extract values from a multidimensional array

I have a very big array with car makes and models. I've already extracted the makes into a separate array, but I am struggling to extract the models while also maintaining their association to the make.
Here is a sample of the array:
var dataa = new Array
(
['Acura','','Integra','Mdx','Rl','Rsx','Slx','Tl','Tsx'],
['Aixam','','400','505','600'],
['Alfa romeo','','145','146','147','155','156'],
['Aston martin','','.','DBS','Db7','Db9']);
As you can see I have a multi-dimensional array with the car make (located at dataa[0][0]), then an empty value and then the model for this make.
I am using this code to to get the car makes:
This gives me the fist value of every nested array -> dataa[i][0]:
for (var i = 0; i < dataa.length; i++) {
document.write(dataa[i][0] + "<br>");
}
My problems start HERE.
I CAN NOT extract all models and assign them to the proper car make. I have tried for-loop's, loops with brakes, while loops and loops with conditional statements but I can't do it.
Please give me some advice here. Would jQuery or some other technology help me?
Put a loop inside your loop.
for (var i = 0; i < dataa.length; i++) {
document.write("<h2>Starting new inner loop!</h2><br>");
for (var j = 0; j < dataa[i].length; j++) {
document.write(dataa[i][j] + "<br>");
}
}
Now for every Array in the outer Array, you're doing a separate loop.
Here's a demo

Categories

Resources