how to use array_push() in JAVASCRIPT? - javascript

I'm new to JavaScript , I have a problem to get new array like
one array result
day = ['sday','mday','tday'];
val = [1,2,3]
when I use array push
var array = [];
$.each(resp.result, function(index, item) {
array.push(item.day);
array.push(item.val );
});
output :- ['sday',1,'mday',2,'tday',3];
but I need
output :- ['sday',1],['mday',2],['tday',3]

I have seen the answer by D.Seah in comment section, But we need answer in answer field also. use
array.push([item.day,item.val]);

Related

delete a Object from an Array stored in localStorage on a specific condition?

I have stored certain information in localStorage like-
$localStorage.recent = [{'id':1,'name':'abc','is_availbale':1},{'id':2,'name':'xyz','is_availbale':1},{'id':3,'name':'pqrs','is_availbale':0}];
having another array which is only having id's of certain people like(array_second can have only those id's which are already there in
$localStorage.recent)-
array_second=['3'];
I want to delete those entries from $localStorage.recent which are corresponding to the id's in array_second. Expected output to be-
$localStorage.recent = [{'id':1,'name':'abc','is_availbale':1},{'id':2,'name':'xyz','is_availbale':1}];
You're just handling a standard array. The ngstorage library doesn't give you any additional functionality here.
For example:
$localStorage.recent = $localStorage.recent.filter((person) => {
return second_array.indexOf(person.id) !== -1;
});
This code may useful to you, written in javascript
var fullArr =[{'id':1,'name':'abc','is_availbale':1{'id':2,'name':'xyz','is_availbale':1},{'id':3,'name':'pqrs','is_availbale':0}];
var toDelArr = [1];
for(var i=0;i<fullArr.length;i++){
if(toDelArr[0] == fullArr[i].id){
fullArr.splice(i, 1);
}
}

access javascript array element by JSON object key

I have an array that looks like this
var Zips = [{Zip: 92880, Count:1}, {Zip:91710, Count:3}, {Zip:92672, Count:0}]
I would like to be able to access the Count property of a particular object via the Zip property so that I can increment the count when I get another zip that matches. I was hoping something like this but it's not quite right (This would be in a loop)
Zips[rows[i].Zipcode].Count
I know that's not right and am hoping that there is a solution without looping through the result set every time?
Thanks
I know that's not right and am hoping that there is a solution without
looping through the result set every time?
No, you're gonna have to loop and find the appropriate value which meets your criteria. Alternatively you could use the filter method:
var filteredZips = Zips.filter(function(element) {
return element.Zip == 92880;
});
if (filteredZips.length > 0) {
// we have found a corresponding element
var count = filteredZips[0].count;
}
If you had designed your object in a different manner:
var zips = {"92880": 1, "91710": 3, "92672": 0 };
then you could have directly accessed the Count:
var count = zips["92880"];
In the current form, you can not access an element by its ZIP-code without a loop.
You could transform your array to an object of this form:
var Zips = { 92880: 1, 91710: 3 }; // etc.
Then you can access it by
Zips[rows[i].Zipcode]
To transform from array to object you could use this
var ZipsObj = {};
for( var i=Zips.length; i--; ) {
ZipsObj[ Zips[i].Zip ] = Zips[i].Count;
}
Couple of mistakes in your code.
Your array is collection of objects
You can access objects with their property name and not property value i.e Zips[0]['Zip'] is correct, or by object notation Zips[0].Zip.
If you want to find the value you have to loop
If you want to keep the format of the array Zips and its elements
var Zips = [{Zip: 92880, Count:1}, {Zip:91710, Count:3}, {Zip:92672, Count:0}];
var MappedZips = {}; // first of all build hash by Zip
for (var i = 0; i < Zips.length; i++) {
MappedZips[Zips[i].Zip] = Zips[i];
}
MappedZips is {"92880": {Zip: 92880, Count:1}, "91710": {Zip:91710, Count:3}, "92672": {Zip:92672, Count:0}}
// then you can get Count by O(1)
alert(MappedZips[92880].Count);
// or can change data by O(1)
MappedZips[92880].Count++;
alert(MappedZips[92880].Count);
jsFiddle example
function getZip(zips, zipNumber) {
var answer = null;
zips.forEach(function(zip){
if (zip.Zip === zipNumber) answer = zip;
});
return answer;
}
This function returns the zip object with the Zip property equal to zipNumber, or null if none exists.
did you try this?
Zips[i].Zip.Count

minimized code for arrays in js

I have three arrays in js and now i want to add empty check on them..so please help me in short/ minimized code for the empty array check.My js code is
var selectedfirst = jQuery('select#frsts').val();
var selectedsecond = jQuery('select#secnds').val();
var selectedthird = jQuery('select#thirds').val();
var lastfindal = selectedfirst.concat(selectedsecond); // Array concatination
var getfinal = lastfindal.concat(selectedthird); // Array concatination
I know how can i process empty check on single array but due to contcatenation the code goes longer . i contcate first array to second then concate to third.I want to concate array when they are not empty. like selectedfirst.length > 0.if anyone not understand fully i will provide more detail on request.Thanks in advance
After working i fix the issue.I created new array like
var hege = [];
if (selectedfirst!== null) {
alert('not emtpy');
var hege = hege.concat(selectedfirst);
}
the same condition for other too.

Add values to end of multidimensional array

I have an array of arrays and I want to be able to add values to the array every time a user hits the add button.
var transactions = [];
transactions[0] = []; // holds date
transactions[1] = []; // holds transaction type
transactions[2] = []; // holds amount
transactions[0][i] = $("date").value;
transactions[1][i] = $("transType").value;
transactions[2][i] = parseFloat( $("amount").value);
these are the snippets . . . I realize I need to work on validation (which I will do) at this point I'm more concerned with loading the arrays. The problem is the method I'm familiar with works with 1-dimensional arrays and I don't know how to replace it.
in short is it possible to reproduce this:
transactions[transactions.length] = $("date").value;
for a multidimensional array.
Thank You
Use push:
transactions[0].push( $("date").value );
You're looking for the Array.push() method. It allows you to push values on to the end of an array.
For your use case, you can do that on both levels of the array. See below:
var transactions = [];
transactions.push([]);
transactions.push([]);
transactions[0].push( $('date').value );
There is no problem for using the same approach:
transactions[0][transactions[0].length] = $("date").value;
or with push method:
transactions[0].push($("date").value);
... keeping in mind that you've initialized transactions[0] with empty array [].
Yes, just idem for multidimensional
transactions[0][transactions[0].length] = var1;
Seems a little weird you are doing:
[[array of transaction dates],[array of transaction types],[array of transaction amounts]]
Are you sure you don't want
[array of transactions, with date,type,amount properties]
?
var transactions = [];
transactions.push({'date': $("date").value, 'type': $("transType").value, 'amount': parseFloat( $("amount").value)});
var i = 0;
alert('date ' + transactions[i].date + ' type ' + transactions[i].type + ' amount ' + transactions[i].amount);

Issue with JSON stringify?

/* Helper function to clean up any current data we have stored */
function insertSerializedData(ids, type) {
// Get anything in the current field
current_data = $('#changes').val();
if (!current_data) {
var data = new Array();
data[type] = ids;
$('#changes').val(JSON.stringify(data));
} else {
var data = JSON.parse($('#changes').val());
data[type] = ids;
$('#changes').val(JSON.stringify(data));
}
console.log($('#changes').val());
}
I am using the following function to either add data to a current JSON object or create a new JSON object all together to be used in PHP later. Is the stringify() method only for FF? I am using google chrome and I am being given an empty object when using the conosole.log() function...
Also what happens if you try to store two values with the same key? I assume it will overwrite...so I should add a random math number at the end array in order to keep duplicates from showing up?
Thanks :)
These lines may cause problems:
var data = new Array();
data[type] = ids;
... because arrays in JavaScript are not quite like arrays in PHP. I suppose what you meant is better expressed by...
var data = {};
data[type] = ids;
Besides, current_data seems to be local to this function, therefore it also should be declared as local with var. Don't see any other problems... except that similar functionality is already implemented in jQuery .data() method.
UPDATE: here's jsFiddle to play with. ) From what I've tried looks like the array-object mismatch is what actually caused that Chrome behavior.
I reformatted it a bit, but and this seems to work. It will set the "value" attribute of the #changes element to a JSON string. I assume that the type argument is supposed to be the index of the array which you're trying to assign?
function insertSerializedData(ids, type) {
var changes = jQuery('#changes'), arr, val = changes.val();
if (!val) {
arr = [];
arr[type] = ids;
changes.val(JSON.stringify(arr));
} else {
arr = JSON.parse(val);
arr[type] = ids;
changes.val(JSON.stringify(arr));
}
console.log(changes);
}

Categories

Resources