JavaScript: Better solution than delete - javascript

I have the following array:
var example = [
function() { /* hello */ },
function() { /* goodbye */ }
];
I use delete example[0]; and am left with the following result:
var example = [
1: function() { /* goodbye */ }
];
Is there a better solution than delete? Or is there a simple way to fix the indexes in the array? (I have jQuery at my disposal)
Edit: I fixed the example array. The indexes were there for the example.

As example is an array, instead of delete, you can use .splice [MDN]:
example.splice(0, 1);
But if examples is actually an object, you'd have to use delete and iterate over all properties and "rename" them. Though it's probably easier to use an array instead.
The reason why you get this result with delete is that you are removing the property '0' from the underlying object and the property '1' still exists. You are basically operating on a lower level.
Another problem with gaps in the indexes is that array.length will always return the the highest index + 1 and not the actual number of values in the array. So after deleting the element, example.length would still be 2.

Your way of defining an array is wrong.
This is how its done:
var example = [
function() { /* hello */ },
function() { /* goodbye */ }
];
you can use shift to remove the first element:
var firstElement = example.shift();

You could use a custom sort function:
array.sort(sortfunction)
function sortfunction(a, b){
// check indexes here
}

You can just shift your first element.
http://jsfiddle.net/4zW7B/1/
var example = [
function() { alert('hello'); },
function() { alert('goodbye'); }
];
example[0]();
example.shift();
example[0]();

Related

Null Values in array of objects

I am creating objects when textbox having some values (using ng-blur and textbox.value!==undefined) and then putting these objects in an array (all working fine here).
When I click on checkbox (checkbox model bind with textbox ng-required) I need to delete that particular object having that textbox value.
I am using:
arr.splice(index,1);
to remove that particular object from array (by matching it's name like "monthly" or "quarterly" etc.), but it is creating null at that particular position.
for e.g. [object,object,object]
[
{name:"monthly",
amount:1000 },
{name:"quarterly",
amount:1200 },
{name:"yearly",
amount:1300 }
]
after removing all element it shows [] and when I add another new object it displays [3:object] and it's content as [null,null,null,object];
or
if I remove middle object say name:"quarterly", it shows [object,object] but after adding a new object it display array as [object,object,null,object] with length of array as 4.
Why is there null and how can I remove that from array. (don't want to iterate again to check null).
It is difficult to say why your code creates the null values without have a look to it.
But I can say you that it is not the expected behaviour.
You can see this example to get some inspiration:
var data = [
{name:"monthly",
amount:1000 },
{name:"quarterly",
amount:1200 },
{name:"yearly",
amount:1300 }
];
var newObjectToBeAdded = { name: "daily", amount:"100" }
function showObjects()
{
document.body.innerHTML += data + '<hr>';
}
function deleteObjectByName( objectName )
{
for( var i = 0; i < data.length; i++ )
{
if( data[ i ].name == objectName )
{
data.splice(i, 1);
}
}
}
function addObjectToData( newObject )
{
data.push( newObject );
}
showObjects();
deleteObjectByName( "quarterly" );
showObjects();
addObjectToData( newObjectToBeAdded );
showObjects();
Just to throw a guess out, maybe you are accidentally duplicating the array. Maybe in some point of your code you are doing something like this:
var new_array = original_array.splice( index );
Or creating the new array in the loop you use to find the target object, or using some kind of intermediate array, etc.
Hope it helps!
var arrayWithoutNulls = myArray.filter(function(val) {
if (val) {
return val;
}
});

How to access a predefined array in AngularJS

I'm facing an issue with accessing the array element in AngularJS. I have an array:
$scope.salesentry = [
{
sales_id:'',
product_id: '',
product_category_id:'',
sale_qty:null,
sale_amount:null
}
];
I want to update the sales_id field value on some button click like:
$scope.saveData = function() {
$scope.salesentry.sales_id='10';
});
I'm not able to access it in the above way. How can I do so?
salesentry is an array, so you need to access a specific element on it first using [0].
So your code becomes:
$scope.saveData = function() {
$scope.salesentry[0].sales_id='10';
});
Do you want to update each salesentry's sales_id ?
If yes you may use
angular.foreach($scope.salesentry, function(value, key){
value.sales_id = 10;
});
You need to index the array
$scope.salesentry[0].sales_id = '10'
Also, no need for the comma at the end.

Delete an element inside a JSON array by value with jQuery

Part of my json Array
var videos = $j.parseJSON('
[
{ "privacy":"public",
"id":"1169341693" },
{ "privacy":"private",
"id":"803641223" },
{ "privacy":"public",
"id":"1300612600" }, ......
When I console.log the element I'm getting
[Object, Object, Object, …]
0: Object
privacy: "public"
id: "1169341693"
1: Object
privacy: "private"
id: "803641223"
2: Object
privacy: "public"
id: "1300612600"
I also have a unique id I want to search for
var uniqueId = 803641223;
I want to find, in my videos array, the right id, and delete that whole array element. So In that case, I want my final videos array to contain only 2 object, instead of 3 :
var videos = $j.parseJSON('
[
{ "privacy":"public",
"id":"1169341693" },
{ "privacy":"public",
"id":"1300612600" }, ......
My problem is how to get in the array to do my splice. I prefer to do it with jQuery
Any help please?
You can use grep :
videos = $.grep(videos, function(e) { return e.id!='803641223' });
In vanilla JavaScript you could have used the similar filter function but it's not supported by IE8.
Please note that videos is a JavaScript array, it's not a JSON array, even if it was made by parsing a JSON string.
A non-jQuery solution that modifies the array in place:
var uniqueId = 803641223;
var videos = [
{ "privacy":"public",
"id":"1169341693" },
{ "privacy":"private",
"id":"803641223" },
{ "privacy":"public",
"id":"1300612600" }
];
function cleaner(arr, id) {
for (var i = 0; i < videos.length; i++) {
var cur = videos[i];
if (cur.id == uniqueId) {
arr.splice(i, 1);
break;
}
}
}
cleaner(videos, uniqueId);
http://jsfiddle.net/4JAww/1/
Note that this modifies the original array in place, such that the original videos array will have the items you want, and the one that matched the uniqueId will be gone (forever). So it depends on whether you want to be able to access the original array ever again, or are okay with modifying it.
It just loops through the elements of the array, compares the item's id property to the uniqueId value, and splices if they match. I use break; immediately after the splice because you seem to imply that the uniqueId can/should only appear once in the array since it's...unique.
Hello you can remove element with javascript splice function...
videos.items.splice(1, 3); // Removes three items starting with the 2nd,
It worker for me.
arrList = $.grep(arrList, function (e) {
if(e.add_task == addTask && e.worker_id == worker_id) {
return false;
} else {
return true;
}
});
It returns an array without that object.
Hope it helps.

how to copy array to array

var ce_info=[
{location:"inchannel",name:"Jae Jung",volume:"50",url:"img/jae.jpeg",group:1},
{location:"inchannel",name:"Houston",volume:"50",url:"img/houston.jpeg",group:1},
{location:"inchannel",name:"Jun kuriha..",volume:"50",url:"img/jun.jpeg",group:1},
{location:"inchannel",name:"Andrea Melle",volume:"50",url:"img/andrea.jpeg",group:0},
{location:"inchannel",name:"Tomoaki Ohi..",volume:"50",url:"img/ohira.jpeg",group:0},
{location:"inchannel",name:"Woosuk Cha..",volume:"50",url:"img/woosuk.jpeg",group:0},
{location:"inchannel",name:"Luca Rigaz..",volume:"50",url:"img/luca.jpeg",group:0},
{location:"inchannel",name:"SooIn Nam",volume:"50",url:"img/sooin.jpeg",group:0}
];
var inch_info=[{location:"ichat",name:"",volume:"50",url:""}];
for(i=0;i<ce_info.length;i++)
{
if(ce_info[i].location=="inchat")
{
inch_info[inchat_count].name=ce_info[i].name;
inch_info[inchat_count].url=ce_info[i].url;
inchat_count++;
}
}
I am trying to copy ce_info to inch_info.
It seems like it does not work.It occurs an error when I try to copy ce_info to inch_info
Any thought?
Copying a native JS Array is easy. Use the Array.slice() method which creates a copy of part/all of the array.
var foo = ['a','b','c','d','e'];
var bar = foo.slice();
now foo and bar are 5 member arrays of 'a','b','c','d','e'
inchat_count seems to be uninitialized.
var inch_info=[{location:"icha",name:"",volume:"50",url:""}];
var inchat_count = 0; // You forgot this line!!
for(i=0;i<ce_info.length;i++)
{
if(ce_info[i].location=="inchat")
{
inch_info[inchat_count].name=ce_info[i].name;
inch_info[inchat_count].url=ce_info[i].url;
inchat_count++;
}
}
You still have a typeO in your code
var inch_info=[{location:"ichat",name:"",volume:"50",url:""}];
shouldnt location be inchat instead of ichat? Because that is what you check for in this line
if(ce_info[i].location=="inchat")
Furthermore in ce_info there is no location named inchat so the result of this piece of code will not be executed. But if there where an element in ce_info that has the location inchat this will be the code you need to add the location and name to the inch_info array.
Change your for loop in this:
for(var eElem in ce_info)
{
if(ce_info[eElem].location=="inchannel")
{
var temp = {};
temp.name=ce_info[eElem].name;
temp.url=ce_info[eElem].url;
inch_info.push(temp);
}
}
using jQuery you can achieve it so easily:
See a working demo here
following jQuery code makes sure that you do not have a by reference object of ce_info.
jQuery code:
var inch_info= jQuery.extend(true, {}, ce_info);
alert("inch_info: before changing text: "+inch_info[0].location);
inch_info[0].location = "hello world"
alert("inch_info: after changing text: "+inch_info[0].location);
alert("ce_info: after changing text: "+ce_info[0].location);

Display elements in my 2d Array in Javascript

I have a post function that returns a 2d array. How would I go about displaying each of the elements in it? My code looks something like this :
$.post("/Question/GetPollQuestionsForView/", { poll_ID: pollId }, function(result) {
//$("#CustomerList tbody").append($(result));
var myarray = new Array()
myarray = result;
alert(myarray);
});
what the alert returns is "System.String[][]". How can i go about appending each of the values from my array to my div tag called #divComparativeQuestions.
For example:
var data = new Array();
for(var i=0;i<myarray.length;i++){
data.push(myarray[i].join(', '));
}
$('#divComparativeQuestions').html(data.join('<br/>'));
(hope this works, not tested :), but you get the idea )
I'm guessing you want something like:
// given an array [[1,2],[3,4]] with a desired result of <div>1234</div>
$.post("/Question/GetPollQuestionsForView/", { poll_ID: pollId }, function(data) {
if(data) {
var div = $('#divComparativeQuestions');
$.each(data, function(index, element) {
div.append(element); // will be inner array of [1,2] or [3,4]
});
}
});
All pretty basic stuff, in this case I'm taking advantage of the fact js typically flattens array as strings without commas to get the desired out put, but if you want to delimit them items somehow or wrap them in tags or whatever, it's easy enough to work out by taking a few seconds to browse http://docs.jquery.com

Categories