Why does array contain only last value n times? - javascript

This function returns the same value in the array list.
For example if i=10, then my array should contain 10 different values, but it stores only the last value 10 times.
What is the problem in my code?
$scope.webTempIds=[];
$scope.wId={};
$scope.getIds=function(){
for(var i=0;i<$rootScope.retData.length;i++){
$scope.wId.ID=$rootScope.retData[i].WEBUI_TEMP_ID;
$scope.webTempIds.push($scope.wId);
}
return $scope.webTempIds;
}

$scope.wId={};
is changed every time. The array contains the reference to this object and hence when you change the value it changes the value in the array.
let obj = {};
let result = [];
for(let i = 0; i<10; i++){
obj.a = i;
result.push(obj);
}
console.log(result);

This happens because you use $scope for wId.ID outside of loop. Therefore your list items point to the same object.
Once you change $scope.wId.ID , the list $scope.webTempIds will be updated too.
To fix it make id local:
for(var i=0;i<$rootScope.retData.length;i++){
var wId = {
ID: $rootScope.retData[i].WEBUI_TEMP_ID;
}
$scope.webTempIds.push(wId);
}
As a side note: use Scope to bind application controller and the view. (inside the for loop you don't need scope)

As others have correctly pointed out, you end up with the last item in the array because the value that you push to the array is on the $scope and gets replaced with the new value each time.
To offer an alternative approach, you could use the Array.prototype.map function to return a new array prepopulated with just the id property values of each data item:
$scope.getIds=function(){
$scope.webTempIds = $rootScope.retData.map(
function(obj){
return obj.id;
}
);
}
This eliminates the need for any loops with temporary variables and any pushing to manually build up a new array from scratch.

$scope.getIds=function(){
$scope.webTempIds=[];
for(var i=0;i<$rootScope.retData.length;i++){
$scope.wId={};
$scope.wId.ID =$rootScope.retData[i].WEBUI_TEMP_ID;
$scope.webTempIds.push($scope.wId);
}
return $scope.webTempIds;
}

Related

Two Dimensional Array - arr[i][0] Gives Wrong Result - JavaScript ASP.NET C#

I have an Array of Arrays populated from C# Model:
var AllObjectsArray = [];
#foreach(var Cobject in Model.ObjectList)
{
#:AllObjectsArray.push(new Array("#Cobject.Name", "#Cobject.Value", "#Cobject.Keyword"));
}
var SelectedObjects = [];
uniqueobj.forEach(function (element) {
SelectedObjects.push(new Array(AllObjectsArray.filter(elem => elem[0] === element))); //makes array of selected objects with their values(name,value,keyword)
});
I am trying to get second parameter of each and every inner Array and add it to new array containing those elements like this:
var ValuesArray = [];
for (i = 0; i < SelectedObjects.length; i++) {
ValuesArray.push(SelectedObjects[i][0]) //problem here i think
};
Unfortunately, on:
alert(ValuesArray + " : " + SelectedObjects);
I get nothing for ValuesArray. The other data for SelectedObjects loads properly with all three parameters correctly returned for each and every inner Array,so it is not empty. I must be iterating wrongly.
EDIT:
SOme more info as I am not getting understood what I need.
Lets say SelectedObjects[] contains two records like this:
{ name1, number1, keyword1}
{ name2, number2, keyword2}
Now, what I need is to populate ValuesArray with nane1 and name2.
That is why I was guessing I should iterate over SelectedObjects and get SelectedObject[i][0] where in my guessing i stands for inner array index and 1 stands for number part of that inner array. Please correct me and put me in the right direction as I am guesing from C# way of coding how to wrap my head around js.
However SelectedObject[i][0] gives me all SelectedObject with all three properties(name, value and keyword) and I should get only name's part of the inner Array.
What is happening here?
Hope I explained myself better this time.
EDIT:
I think I know why it happens, since SelectedObjects[i][0] returns whole inner Array and SelectedObjects[i][1] gives null, it must mean that SelectedObjects is not Array of Arrays but Array of strings concatenated with commas.
Is there a way to workaround this? SHould I create array of arrays ddifferently or maybe split inner object on commas and iteratee through returned strings?
First things first, SelectedObjects[i][1] should rather be SelectedObjects[i][0].
But as far as I understand you want something like
var ValuesArray = [];
for (let i = 0; i < SelectedObjects.length; i++) {
for(let j = 0; j <SelectedObjects[i].length; j++) {
ValuesArray.push(SelectedObjects[i][j]);
}
};
In this snippet
var ValuesArray = [];
for (i = 0; i < SelectedObjects.length; i++) {
ValuesArray.push(SelectedObjects[i][1]) //problem here i think
};
You're pointing directly at the second item in SelectedObjects[i]
Maybe you want the first index, 0

Appending an array with multiple arrays in google script

I have an array where I send a set of values after an operation on a spreadsheet followed by taking the average.
Now I want to return each row also along with the above data.
I thought of using two-dimensional arrays.
But I have less clarity in implementing this.
for (var i = 0; i < spreadsheetRows.length; i++)
{
//operations done and variables updated
variable1=
variable2=
variablen=
}
var sendArray = [];
sendArray.push(variable1);
sendArray.push(variable2);
sendArray.push(variable3);
sendArray.push(variable4);
return sendArray;
Now i want to send the array rowFirst & rowSecond also
for (var i = 0; i < spreadsheetRows.length; i++)
{
//first row of spreadsheet
rowFirst=[]; //data of first row
rowSecond=[]; //data of second row
//operations done and variables updated
variable1=
variable2=
variablen=
}
var sendArray = [];
sendArray.push(variable1);
sendArray.push(variable2);
sendArray.push(variable3);
sendArray.push(variable4);
sendArray.push(rowFirst); // stuck here <---
sendArray.push(rowSecond);// stuck here <----
return sendArray;
How to send the array with these two data( ie rowFirst and rowSecond) . Please guide me.
Output Expected
sendArray=[
var1,
var2,
var3,
varn,
rowFirst=[num1, num2, num3,...numn]
rowSeocnd=[num1, num2, num3,...numn]
]
To answer your immediate question, you can push an array into another array by using square brackets in push.
sendArray.push([rowFirst]);
sendArray.push([rowSecond]);
Based on your comment, you may want to use an Object, not an Array (here's a helpful article on the differences). So, think through why you'd want four variables not associated with anything. Can those be grouped or keyed somehow? There are a number of ways to do this and a simple method is to use dot notation to pair a variable or a data set to an object key.
// declare the object and each array
var sendObject = {}
// from your code...
for (var i = 0; i < spreadsheetRows.length; i++)
{
//operations done and variables updated
variable1=
variable2=
var rowFirst = [variable1, variable2, ...]
}
// Create the key in the Object and assign the array
sendObject.rowFirst = rowFirst;
The output would be:
sendObject = {
"rowFirst": [variable1, variable2, ...]
}

Add to array only once - leaving unique items

I program a function that give me all values of some input checkboxes and include them into an array.
Function:
$('#area_tbl .checkbox').each(function(){
/*for(var i = 0; i < test.length; i++){
if(test[i].PLZ === $(this).find('.area-checkbox').val()){
alert('Gleich');
}else{
alert('nicht gleich');
}
}*/
test.push({PLZ:$(this).find('.area-checkbox').val()});
});
My array looks like this:
[Object { PLZ="42799"}]
That's fine!
Now I include automatically more checkboxes with more values. After that my function is refreshing and I include the 'new' values.
Now my problem is that my array looks like this:
[Object { PLZ="42799"}, Object { PLZ="42799"}, Object { PLZ="51399"}]
You can see PLZ='42799' is twice.
I want to find the duplicate values and delete them from my array. I try it with the if clause in my function. But nothing works for me.
Assuming that value of each checkbox is unique, you need to reset the test value before running this each iterator
test = [];
$('#area_tbl .checkbox').each(function(){
test.push({PLZ:$(this).find('.area-checkbox').val()});
});
You could use a memory
// The memory will be a simple list with the already added elements. Firstly empty
memory = []
// we loop over ther checboxes
$('#area_tbl .checkbox').each(function(){
// we store the value
var v = $(this).find('.area-checkbox').val();
// If memory doesn't content the value... (its position is -1)
if(memory.indexOf(v) == -1){
// we store the object and we update the memory
test.push({PLZ:v});
memory.push(v);
}
});
You could use a temporary object and look up with accessing the property:
var object= {};
$('#area_tbl .checkbox').each(function() {
var v = $(this).find('.area-checkbox').val();
if (!object[v]) {
test.push({PLZ: v});
object[v] = true;
}
});

json stringify result get value on specific key

[{"displayorder":"1","menuname":"DashBoard","menuid":"5","menuurl":"dashboard.php"},{"displayorder":"3","menuname":"Accounting Module","menuid":"3","menuurl":""},{"displayorder":"4","menuname":"My Profile","menuid":"4","menuurl":"myprofile.php"},{"displayorder":"6","menuname":"HR Module","menuid":"2","menuurl":""},{"displayorder":"9","menuname":"Administrator","menuid":"1","menuurl":""}]
I have here a stringfy json i want to know how to get a value of all the menuname in this json object any idea appreciated
UPDATE:
I tried this one
here but I get undefined in console
UPDATE
[{"displayorder":"1","menuname":"Menu Management","menuid":"1","submenuurl":"","parentid":"1"},{"displayorder":"1","menuname":"hr sub menu","menuid":"7","submenuurl":"error.php","parentid":"2"},{"displayorder":"2","menuname":"Role Management","menuid":"2","submenuurl":"","parentid":"1"},{"displayorder":"2","menuname":"menu 2 management2","menuid":"8","submenuurl":"","parentid":"2"},{"displayorder":"3","menuname":"hrsubmenu","menuid":"3","submenuurl":"contactus.php","parentid":"2"},{"displayorder":"3","menuname":"submenuaccounting","menuid":"4","submenuurl":"imagegallery.php","parentid":"3"}];
how to get all all details in the second json with parentid depending on above menuid?
Working example:
http://jsfiddle.net/0866pay3/
var json = [{"displayorder":"1","menuname":"DashBoard","menuid":"5","menuurl":"dashboard.php"},{"displayorder":"3","menuname":"Accounting Module","menuid":"3","menuurl":""},{"displayorder":"4","menuname":"My Profile","menuid":"4","menuurl":"myprofile.php"},{"displayorder":"6","menuname":"HR Module","menuid":"2","menuurl":""},{"displayorder":"9","menuname":"Administrator","menuid":"1","menuurl":""}];
json.forEach(function(el, idx){
console.log(el.menuname);
});
Documentation Update
If you check out this article, you'll see the following:
callback is invoked with three arguments:
the element value
the element index
the array being traversed
So, idx is just a common way of representing the element index. You can call this whatever you'd like - theIndex, myRandomName, etc.
var myjson = [{"displayorder":"1","menuname":"DashBoard","menuid":"5","menuurl":"dashboard.php"},{"displayorder":"3","menuname":"Accounting Module","menuid":"3","menuurl":""},{"displayorder":"4","menuname":"My Profile","menuid":"4","menuurl":"myprofile.php"},{"displayorder":"6","menuname":"HR Module","menuid":"2","menuurl":""},{"displayorder":"9","menuname":"Administrator","menuid":"1","menuurl":""}];
var menu_names = [];
for (var x = 0 ; x < myjson.length; x++){
if(myjson[x].hasOwnProperty('menuname')){
// do something usefull here
console.log(myjson[x]['menuname']);
// add value to new array
menu_names.push(myjson[x]['menuname'])
}
}
console.log(menu_names);

Items in array returning last one only

I am using this function to pass every element in an array to use it in an if statement The problem is that the function is always returning the last value of the array Please help.
function getQtyCheck()
{
var qty;
var id;
var checkQty = new Array()
if(localStorage.getItem("checkout")!=null || localStorage.getItem("checkout")!=""){
checkQty = JSON.parse(localStorage.getItem("checkout"));
for(var t =0; checkQty.length >t; t++){
id = checkQty[t];
t++;
qty = checkQty[t];
}//end for loop
return {ids:id,qtys:qty}
}//end checkout
}
Then in another part of the script I ma using these variables like this
var result = getQtyCheck();
var id = result.ids;
var qty = result.qtys;
if(this.id == id){
var tqty = this.quantity-qty;
Each loop iteration, you assign id and qty to the currently iterated item. Once the loop is over, you return an object with the LAST iterated item set to your variables. Since your return is immediately after the loop and using variables set within the loop, you will always get the last values.
I think I'm following what you are trying to do now. You want to return every element in the array as an array of objects right?
function getQtyCheck() {
var qty,
id,
checkQty = [],
returnValues = [];
if(localStorage.getItem("checkout")!=null && localStorage.getItem("checkout")!=""){
checkQty = JSON.parse(localStorage.getItem("checkout"));
for(var t =0, len = checkQty.length; len > t; t++){
id = checkQty[t];
t++;
qty = checkQty[t];
returnValues.push({ id: id, qty: qty });
}
return returnValues;
}
}
In the loop, build an array of the objects you want to return. After the loop, return the newly created array.
It's returning the last one every time because you're looping it which is adding it up, but then you're using return outside the loop, which is just going to get the last one that it ran.
You shouldn't return inside the for loop because it will try to return multiple times. What you can do though is push it to an array and then get it at the end.

Categories