Why is JavaScript returning the wrong array length?
var myarray = ['0','1'];
delete myarray[0];
alert(myarray.length); //gives you 2
The "delete" doesn't modify the array, but the elements in the array:
# x = [0,1];
# delete x[0]
# x
[undefined, 1]
What you need is array.splice
you have to use array.splice - see http://www.w3schools.com/jsref/jsref_splice.asp
myarray.splice(0, 1);
this will then remove the first element
According to this docs the delete operator does not change the length ofth earray. You may use splice() for that.
From Array's MDC documentation:
"When you delete an array element, the
array length is not affected. For
example, if you delete a[3], a[4] is
still a[4] and a[3] is undefined. This
holds even if you delete the last
element of the array (delete
a[a.length-1])."
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator
https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array
You can do this with John Resig's nice remove() method:
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
than
// Remove the second item from the array
array.remove(1);
// Remove the second-to-last item from the array
array.remove(-2);
// Remove the second and third items from the array
array.remove(1,2);
// Remove the last and second-to-last items from the array
array.remove(-2,-1);
That's the normal behavior. The delete() function does not delete the index, only the content of the index. So you still have 2 elements in the array, but at index 0 you will have undefined.
Related
Here is my code:
let num = 0.0134;
console.log(num.toString().split('').splice(3).splice(1, 0, '.'))
The console.log returns an empty array.
I want it to return '1.34'. What am I doing wrong?
If you see the reference for Array.prototype.splice on mdn:
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place
Return Value: An array containing the deleted elements.
At the end of your code, when you do .splice(1, 0, '.'), it deletes 0 elements so it will return an empty array.
I'm assuming you want to get the previous array with the '.' element inserted in the first position. For that you'll want to do:
const arr = num.toString().split('').splice(3);
arr.splice(1, 0, '.');
console.log(arr)
And If you want to join it to a string just use arr.join('')
Anyway, for your use case, you could just use the * multiplication operator rather than converting to a string array and attempting to manipulate that.
You can simply do:
let num = 0.0134;
console.log(num * 100);
I have the following function, which pretty much does what it supposed to, but I would like to understand exactly what it does on each steps of its loop.
Could you please take a look to the function below and give me a clear explanation commenting each step or the Filter and IndexOf methods?
Thank you very much in advance.
var arr = [6,2,6,8,9,9,9,4,5];
var unique = function(){
return arr.filter(function(e, i, a) {
return i === a.indexOf(e);
})
}
unique();
indexOf returns the first index of an element in an array:
[1,2,2,3].indexOf(2); // 1
So if you use filter as in your example when it gets to the second occurance of an element the index (i in your example) will not be equal to the value returned by indexOf and be dropped. In my array above the second 2 is at position 2 which obviously doesn't strictly equal the one returned by indexOf.
[1,2,2,3].filter((value, index, array) => array.indexOf(value) === index);
// first iteration: value is 1, index is 0, indexOf is 0 0===0 keep 1
// second: value is 2, index is 1, indexOf is 1, 1===1 keep 2
// third: value is 2, index is 2, indexOf is 1, 1===2 false! toss 2
// etc.
The end effect is that any duplicate elements get dropped from the copy returned by filter. And it is a copy, the original array is not mutated.
EDIT
I should probably mention that recent versions of JavaScript give us a better way:
let arrayWithDupes = [1,2,2,3];
let uniq = Array.from(new Set(arrayWithDupes)); // [1,2,3]
If log the values like:
var arr = [6,2,6,8,9,9,9,4,5];
var unique = function(){
return arr.filter(function(e, i, a) {
console.log('e: ' + e);
console.log('i: ' + i);
console.log('a: ' + a);
return i === a.indexOf(e);
})
}
var unq = unique();
console.log(unq);
you will get:
"e: 6"
"i: 0"
"a: 6,2,6,8,9,9,9,4,5"
and so on...
e = current element from array, i = index of the array, a = array source;
Filer function: "The filter() method creates an array filled with all array elements that pass a test (provided as a function)."
indexOf: "The indexOf() method searches the array for the specified item, and returns its position."
I'm looking at an exercise and having trouble understand how the following works ( I'm trying to remove duplicates from an array)
var arr = ['a','b','c','a','b','d','e','f'];
var uniqueArray = arr.filter(function(item,pos){
return arr.indexOf(item) == pos;
});
My attempt to understand
Here item takes on all of our values in arr. Lets go through an iteration
First item = 'a' and pos = 0. Ok. now we want to only filter on the basis of if the index of 'a'is the same as 0
Here indexOf(a) == 0.
Great! this is true, lets put it in the new array.
Now lets move forward to where we see a again, namely at pos = 3
arr.indexOf(a) == 3
Wait... Doesent this meet our requirement as well? How does this even remove duplicates?
indexOf returns just one integer value, and it is the index of the first found item. So, when pos is 3 (and the item is a), indexOf will return 0 (because the first index of a is 0), 0==3 is false and the element will be removed.
Then, when the pos is 4 (and item is b), indexOf returns 2, the index of the first found b.
As for the objects, they can't have duplicate keys. Each new key will automatically overwrite the old one, so there won't be any duplicates.
Look:
var obj = {a:1, a:3, b:2,c:5,b:4};
console.log(obj)
nicael is right. indexOf(item) is just a function that goes through the array and looks for the first time item appears in the array, and returns the position in the array. In your example, if there is an a at 0 and a at index 3, then indexOf('a') will return position 0, while the value of pos is 3, so the filter returns false.
FOLLOW UP:
indexOf() has another parameter called the fromIndex, which lets you start the search from a position other than the beginning of the array. In this case, you can specify to skip over the first time 'a' occurs by doing arr.indexOf('a', 1) which starts the search at position 1, not 0. In this case the function would return true since the next 'a' is at position 3.
Can I use filter on an object?
No, because filter is a specific function of an Array object. You can get the keys of the object by doing a filter on Object.keys(myObject) since keys() returns an array.
Using your example:
var keyArray = Object.keys(myObject); //object can't have duplicate keys
keyArray.filter(function(item, index) {
return keyArray.indexOf(item) == index; //will never be false
});
Hashtable is the best way to eliminate the redundant values
Here is the code :
char arr[] = ['a','b','c','a','b','d','e','f'];
//it will contains all 26 places as zero (A - Z)
char hashArray[26]={0}
int i; //for iteration;
for(i=0;arr[i]!='\0';i++)
{
//it will subtracte the ascii value of the letter
//from 'a' so that we have the values from 0 to 26)
hashArray[arr[i]-'a']=arr[i];
}
for(i=0;i<26;i++)
{
if(hashArray[i]!=0) //to Ensure the positon has the character
{
printf("%c",hashArray[i]);
}
}
I have an array:
array = ['mario','luigi','kong']
I call its splice function to remove all items before an index:
array.splice(1) //-> ['luigi','kong']
I'm just wondering if there is a function similar to splice to remove all items after an index:
pseudo code
array.mirrorsplice(1) //-> ['mario','luigi']
Use Array.length to set a new size for an array, which is faster than Array.splice to mutate:
var array = ['mario','luigi','kong', 1, 3, 6, 8];
array.length=2;
alert(array); // shows "mario,luigi";
Why is it faster? Because .splice has to create a new array containing all the removed items, whereas .length creates nothing and "returns" a number instead of a new array.
To address .splice usage, you can feed it a negative index, along with a huge number to chop off the end of an array:
var array = ['mario','luigi','kong'];
array.splice(-1, 9e9);
alert(array); // shows "mario,luigi";
Though assigning a shorter value to the array length(as #dandavis said) is the fastest and simplest way to remove trailing element from an array, you can also do that using a similar method like splice which is known as slice.
Like following:
array = ['mario', 'luigi', 'kong'];
array = array.slice(0, 2); //Need to assign it to the same or another variable
console.log(array); //["mario", "luigi"]
As you can see you need to store the returned value from slice method. To understand 'why', here are the major distinction between slice and splice method:
The splice() method returns the removed item(s) in an array and slice() method returns the selected element(s) in an array, as a new array object.
The splice() method changes the original array and slice() method doesn’t change the original array.
To remove all items after an index:
var array = ['mario','luigi','kong'],
index = 1; // your index here
array = array.splice(index + 1, array.length - (index + 1) );
// 3 - (1+1) = 1
// 1 is the remaining number of element(s) in array
// hence, splice 1 after index
Result:
['mario', 'luigi']
You need to +1 since splice starts removing at the index.
I think you misunderstood the usage of Array.prototype.splice(). It already does what you asked for (remove everything after an index, read below paragraph for correction) and it does return the deleted values. I think you got confused with the returned value as the current value of the array.
Array.prototype.splice() however, removes the provided index value too, which is basically equivalent of setting the length of the array. So if you call it as array.splice(2), it'll set the length to 2 and everything including the values at index 2 and after will be deleted. This is provided that the current length of the array is greater than the first parameter provided to Array.prototype.splice().
For example:
const array = ['mario','luigi','kong'];
const deletedItem = array.splice(1);
console.log(array); // ['mario']
console.log(deletedItem); // ['luigi','kong']
For more information: refer to the MDN doc.
You can use splice. Here is a demo.
var array = ['mario','luigi','kong']
To remove all the elements after an index:
var removedElement = array.splice(index, array.length)
removedElement will have the list of elements removed from the array.
example:
let index = 2;
var removedElement = array.splice(2, array.length);
removedElement = ["kong"];
array = ["mario", "luigi"];
I have an array in javascript. I have to find last value of that array.
My code is like
var array= fruits;
and I have to find last fruit in that array.
Since in JavaScript arrays of size n are indexed from [0..n-1], you can get the last element by simply indexing the array at n-1, where is the length of the array and can be obtained by the .length property:
var lastFruit = array[array.length - 1];
If you want to get the last element and also remove it from the array, you can use the .pop methid:
var lastFruit = array.pop(); // get last element of array and remove it from array
Note: As RobG stated:
length is at least one more than the highest index, but might be
greater
First find number of elements in array and store it on variable like
var total = array.length;
Now you can find last value of array using below code
var last = array[total-1];
You accomplish this by using the length of the array (fruits.length) and subtracting 1 (because the array is 0 indexed). For instance...
fruits[0]="pear";
fruits[1]="apple";
fruits[2]="peach";
So fruits.length would be 3, so fruits.length - 1 = 2. So to get the last element...
var lastFruit = fruits[fruits.length-1];
I have to find last value of that array
The length property is at least one higher than the highest index, however it might be higher in which case the n-1 member may not exist. E.g.
// Create an array with length 10
var a = new Array(10);
// Add one member at index 0
a[0] = 'foo';
So the "last" value of the array is at index 0 and has a value of "foo". So you can start with length - 1 and search backwards for members that actually exist:
function lastValue(arr) {
var i = arr.length;
while (i--) {
if (i in arr) {
return arr[i];
}
}
// If get to here, arr has no members
return -1;
}
// All the following arrays have length 4 but different number of members
console.log(lastValue([ , , , ,])); // -1, i.e. there are no members
console.log(lastValue([0,1, , ,])); // 1
console.log(lastValue([0,1,2,3 ])); // 3
console.log(lastValue([ , , ,3 ])); // 3
If you know the Array only has numeric members (i.e. there are no non-numeric properties and no negative properties) you can do:
var arr = [,,'foo',,'bar',,]; // length 6, highest member is at index 4
console.log(arr[Math.max.apply(Math, Object.keys(arr))]); // 'bar'
Requires ES5 Object.keys.
Well you can find it's length then you know the last index, and can get the item from it
var last_item = array[array.length - 1];
Its as easy as:
fruits[fruits.length-1]