I have an array:
data.Dealer.car[0]
data.Dealer.car[1]
data.Dealer.car[2]
If I do this:
alert(data.Dealer.car.length);
delete data.Dealer.car[1];
alert(data.Dealer.car.length);
It gives me the same count each time. Does the removed element still exist?
If you want to remove an item, use the splice method:
alert(data.Dealer.car.length);
data.Dealer.car.splice(1, 1);
alert(data.Dealer.car.length);
But notice that the indices have changed.
JavaScript arrays aren't sparse, if you have a 0 and a 2, then element 1 must exist. Meaning the length is going to be 3.
Array.shift() would remove the first item from the array and make it shorter.
Array.pop() will remove the last item.
Building on what #Ray Hidayat posted:
JavaScript arrays are sparse. If you have an array of length 3, deleting the reference at [1] will simply "unset" that item, not remove it from the array, or update that array's length. You could accomplish the same with
myArray = [0, , 2, , , , ]; // length 6; last three items undefined
Here's a Fiddle:
http://jsfiddle.net/WYKDz/
NOTE: removing items from the middle of large arrays can be computationally intensive. See this post for more info:
Fastest way to delete one entry from the middle of Array()
I think you're looking for this:
var arr = [0,1,2,3,4];
alert( arr.splice( 2, 1 ) ); // alerts 2, the element you're removing
alert( arr ) // alerts 0,1,3,4 - the remaining elements
here's a MDC reference
Ok.. fixed this now as the array was still allocated.
I needed to basically do:
var newCar = new Array();
for (i = 0 ; i < tblSize -2; i ++)
{
newCar[i]=data.Dealer.car[i];
}
data.Dealer.car = newCar;
Related
I'm wondering if it's possible to pull a certain number of elements out of a Javascript array and insert them into a new array, while using one of the elements as a reference point?
This is what I'm trying to do, imagine I have an array like this:
var firstarray = [
475387453,
286235425,
738264536,
196792345,
834532623,
253463455,
535273456];
And then I have a variable that equals the number 286235425:
var element = 286235425;
I have another variable that equals the number 3:
var thenumber = 3;
What I want to do is go through the array, select the 3 elements that come after the ''var element'' number, and store them in a new array named "second array".
So with the above example the result should be:
var secondarray = [
738264536,
196792345,
834532623];
I've seen some questions that talked about filtering array elements, but I haven't been able to find anything about selecting elements in the above way. Is such a thing even possible?
I know it's possible to trim elements from the beginning and end of the array, but as the array will always be a different length whenever the function runs, this method isn't suitable for this problem.
Any help with this would be really appreciated,
Thank you in advance!
You can do this with splice and indexOf
var firstarray = [
475387453,
286235425,
738264536,
196792345,
834532623,
253463455,
535273456
], element = 286235425, thenumber = 3;
var secondarray = firstarray.splice(firstarray.indexOf(element)+1, thenumber);
console.log(secondarray)
Grab the index where element is in the array using indexOf:
var index = firstarray.indexOf(element);
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
Use slice to grab the elements from the array from the next index to the next index + thenumber
var secondarray = firstarray.slice(index + 1, index + 1 + thenumber);
The slice() method returns a shallow copy of a portion of an array into a new array object.
DEMO
I have an object which has duplicate values so i used delete new_object[1] to delete the value but when I see this in console its showing undefined in object 0800
["293", undefined, "298", "297"]
You should use
arr.splice(index, 1);
delete only removes the element, but keeps the indexes. This question is similar in nature and provides more information.
I think you should use splice
a = ["1","2","3"];
a.splice(1,0)
console.log(a) //["1","3"]
var test = [1,2,3,4];
delete test[1];
now if you print the test variable, you will get
=> [ 1, , 3, 4 ]
that is why you have got undefined
like everyone here is answering, you should use splice
test.splice(1,1);
and now print the test variable will give you
=> [ 1, 3, 4, 5 ]
you need to use splice() in order to remove the value from the array. What you are doing is simply setting it to undefined.
var myArray = ['295', '296', '297', '298'];
// removes 1 element from index 2
var removed = myArray.splice(2, 1);
// myArray is ['295', '296', '298'];
// removed is ['297']
Reference from Array.splice
The splice() method changes the content of an array by removing
existing elements and/or adding new elements.
I want to clone a new array from an existing one and push in an element.
Unfortunately, the existing array is an empty one, so it's like:
[].slice().push(65)
the output of above expression is 1.
Why is it 1?
Array#push() returns the length of the resultant array. Since you're pushing a single value onto an empty array, the length of the result will indeed be 1.
If you want to see the updated array as output, you'll need to save a reference to it since push() does not return a reference:
var arr = [].slice();
arr.push(65);
console.log(arr); // [ 65 ]
Changing my comment to an answer:
MDN push(): The push() method adds one or more elements to the end of an array and returns the new length of the array.
You need to do it in two steps, not one with that pattern.
var temp = [].slice();
temp.push(65);
console.log(temp);
If you want to do it in one line, look into concat()
var a = [1,2,3];
var b = [].concat(a,64);
console.log(b);
In JavaScript, if you set an array to be of size 5 ( var foo = new Array(5); ), is this just an initial size? Can you expand the number of elements after it is created. Is it possible to do something like this as well - arr = new Array() and then just assign elements one by one? Thanks in advance :-)
Yes it is just an initial size, and it is not required. If you don't use a single number, you can immediately populate.
It is also more common to use the simpler [] syntax.
var arr = ['something', 34, 'hello'];
You can set (or replace) a specific index by using brackets:
arr[0] = "I'm here replacing whatever your first item was";
You can add to the end by using push:
arr.push('add me');
There may be faster performance in some browsers if you do it like this instead:
arr[arr.length] = 'add me';
You can add something at any index.
You can remove an item completely using splice:
arr.splice(0, 1); // remove first item in the array (start at index 0, with 1 being removed)
When you give a new array an explicit size in javascript (using new Array(5)), you populate each index with value of undefined. It is generally considered better practice to instantiate using the array literal [] expression:
var arr = [];
Then, you can push new elements using push()
var arr = [];
arr.push('first value'):
arr.push('second value'):
Check out the MDC Array documentation for more info: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array
Theres a few ways to declare and put values in an array.
First like what you want to do,
var myarr = new Array();
myarr[0] = 'element1';
myarr[1] = 'element2';
myarr[2] = 'element3';
Second way is to define them
var myarr =new Array("element1","element2","element3");
and third is similar to the second
var myarr =["element1","element2","element3"];
You can also check out https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array for a little more information about using the arrays as well. You could use push and pop if you wanted to as well.
If you use jquery or mootools they also have built-in functions to perform on arrays,
http://api.jquery.com/jQuery.each/ for instance.
Have a look at http://www.w3schools.com/js/js_obj_array.asp
var myCars=new Array(); // regular array (add an optional integer
myCars[0]="Saab"; // argument to control array's size)
myCars[1]="Volvo";
myCars[2]="BMW";
Check the documentation for Array, but the simple answer to your question is yes.
var arr5 = new Array(1, 2, 3, 4, 5); // an array with initial 5 elements
var arr = new Array(); // an array without initial
You can also use array literals:
var arr5 = [1, 2, 3, 4, 5];
var arr = [];
Arrays are dynamic in JavaScript. You don't have to initialize them with a certain length. In fact you should use the literal notation [] because of the Array constructor's ambiguity:
If you pass only one parameter to Array, it will set the array length to this parameter. If you pass more than one parameter, these elements are added to the array.
How is the size of the array determined?
The size of an array is the highest index + 1. This can be quite confusing. Consider this:
var arr = [];
arr[41] = 'The answer?';
console.log(arr); // [undefined, undefined, ..., 'The answer?']
console.log(arr.length) // 42
You can even set the length yourself by assigning a number to .length:
arr.length = 99;
If you now add a new element using arr.push(), it will get the index 100 and the length will increase. Whenever you add an element to the array via an index, it is tested whether arr.length is smaller than the index and updated accordingly. But it does not get smaller.
So in fact what var arr = new Array(5) is doing is setting the length of the array to 5. Nothing else.
For more information about creating and populating arrays, I suggest to read about it in the MDC JavaScript Guide.
Just a simple question that I can't seem to find the answer to.
myarray.length()
The above will return the length including deleted items. How do I get the length without deleted items? Thanks
EDIT:
Thanks for the answers. I am deleting by writing 'delete myarray[0]' and this works well. Other sections of the script rely on the length() method to return the length including deletes. The splice method looks like what I want, so I'll try this
I think that you are deleting your array elements by using the delete operator.
This operator removes the element at the index you specify, but the array length is not affected, for example:
var a = [1,2,3];
delete a[0];
console.log(a); // results in [undefined, 2, 3]
If you want to delete the elements and shift the indexes, you can use the splice function:
var a = [1,2,3];
a.splice(0,1);
console.log(a); // [2, 3]
You could implement a simple function to remove elements in a given index:
Array.prototype.removeAt = function (index) {
this.splice(index,1);
};
If for some reason you do want to use sparse arrays (totally legitimate) but want to count the number of defined elements, you can just use reduce(), for example:
var arr = [1, 2, undefined, 3, undefined, undefined, 4];
arr.reduce(function(prev, curr) {
return typeof curr !== "undefined" ? prev+1 : prev;
}, 0); // evaluates to 4
reduce() is supported by all modern browsers, IE9+. For older browsers there's a polyfill and more info over at MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
You can use for..in loop, which ommits deleted items.
var a = [1,2,3,4,5];
delete a[0];
delete a[1];
for(var i=0;i<a.length;i++){}
console.log(i); //5
var j=0;
for(var i in a){j++;}
console.log(j); //3
John Resig (author of jQuery) wrote a function that (really) removes items from an array in Javascript. If you use this function instead of the delete operator, you should get an accurate count from the array after the deletion.
http://ejohn.org/blog/javascript-array-remove/