I am trying to understand more about Javascript Array.indexOf function
var array = [1,2,3,4,5,1,2,3,4,5,6];
console.log(array.indexOf(2)); //return 1
console.log(array.indexOf(2,3)); //returns 6
console.log(array.indexOf(2,10)) //returns -1
console.log(array.indexOf(4,4)); //returns 8
I know first param return the index of the number in the Array. What is the use of 2nd param and when do we use it?
Thanks
The first parameter is the value to be found.
The second parameter is the starting index.
So:
indexOf(2, 3)
Means find the first occurrence of 2 starting at index 3.
The link provided by #Roko shows some useful examples of this with some additional detail.
Related
a = ['a','b','c','d','e'];
console.log(a.splice(1));
console.log(a);
In splice documentation, it says that skipping the delete parameter will delete all array items, yet here they're not; the first one is left out. Why is this?
Edit: My expectations was that haveing the omission of the delete parameter would cause to delete all the items of the array. But now after read Baconnier comment I understand that removes all after the index (first parameter).
then all the elements from start to the end of the array will be deleted. start being 1 in your case.
a = ['a','b','c','d','e'];
console.log(a.splice(0));
console.log(a);
Arrays start at 0, if you want to delete all elements including the first one you need to pass 0 as the first parameter.
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// expected output: 1
// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4
console.log(beasts.indexOf('giraffe'));
// expected output: -1
I've been repeatedly looking at this js syntax. I've got this code from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
It says that the fromIndex parameter is the index to start the search at. Now, from the code above, I'm confused about how the counting from the fromIndex parameter happens. From the code on the line:
// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4
Camel is the item with index 2. How does the counting happen to arrive with an expected output of 4?
When I try to change the 2nd parameter,
// start from index 3
console.log(beasts.indexOf('bison', 3));
Duck is the item with index of 3. But the output that comes for indexOf('bison', 3) is still 4.
How does the counting really happen?
Nothing gets counted here, it just outputs you the index where the element is at.
If you type in console.log(beasts.indexOf('bison', 3)); then you start your search from index 3. You will still get 4 because bison is at index 4. Even the name indexOf says that you receive the index.
The array stays the same, just the starting point is moved to index 3
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
^
|
|
You start here and search to the right for "bison"
Very simple.
First element index is 0:
> console.log(beasts[0])
"ant"
indexOf will loop your array if you pass the second parameter.
In other words, if element was not found from the index you pass till its end, the command will continue looking for it from its beginning, continuing the counting.
It is not a matter of counting here. It's all about the position of an element in a zero-index based array.
Maybe you get confused because you get for the same word (bison) two indexes. No worry. Don't forget that that word is repeated twice in the array. Without even using indexOf you can see that it is in index 1 and index 4.
I'm having trouble with the following code (will explain after) within a Vue SPA component:
const accountArray = Array.from(Object.values(this.accounts)[0]) // [0 is the sub-array I need, and won't change]
const urlId = this.$route.params.id // 3
const i = accountArray.findIndex(account => account.id === urlId) // -1
console.log(i) // -1, as it didnt found any matches
console.log(urlId) // 3
The this.accounts is a computed property that returns an Observable object, and it works as expected (the 0 index is the sub-array of interest), hence my looping on it. The accountArray variable also returns the array that I want to iterate over (it has an account with id = 3), but when it comes to the iteration predicate, it ALWAYS returns -1 when it should be returning 2. Also, if I hard-code 3 instead of urlId, it returns the 2 that I'm looking for. Why?
When I print the accountArray, the output is the following:
I've made sure that this is not a Vuex reactivity problem, because I can refresh the page and it still returns me the arrays I need. What I'm missing here?
Thanks in advance!
You're using === comparison which expects the same value and same data type which is not true for your case. Your account.id is number and your urlId coming from route params is a string (3 !== "3").
Try converting route params id to a number before comparing it to account.id.
const urlId = +this.$route.params.id // 3
Notice + sign in front of this.$route.params.id used to convert a string to a number.
As an alternative, you could compare it using == which would return true for your 3 == "3" case, but I suggest you to stick to the first advice.
function getFileExtension(i) {
if (i.indexOf(".") < 0) {
return false;
}
var filenameParts = i.split(".");
return filenameParts[filenameParts.length-1];
}
Here's the whole code. I understand it all except for the last line. I know what it does, but I don't know how or why. The second to last line splits the string at the ".", and then how does the last line actually get all the letters on the right side of the string?
By calling var filenameParts = i.split("."); an array is created containing the different parts. Imagine we use the filename test.txt and we use that string to split, we'll get an array like so:
filenameParts = ["test", "txt"]
Because the index of the first item in an array is 0, and we need the last item in the array, we call filenameParts.length-1 to get to the last item.
More information about javascript arrays can be found here.
The .split() function returns an array of strings, not a string. The expression filenameParts[filenameParts - 1] fetches the last element of the array.
filenameParts.length delivers the count of the filenameparts, split in the line above. filenameParts[number] delivers the one item of the array, which is positioned at number. -1 because arrays start at 0 not at 1. So it delivers the last item of the array. Clear?
filenameParts is an array and you read a single value with it's index. A value in this case is one part of the string between the ".".
filenameParts.length is equal to the count of values inside the array. As an array index starts with 0 you have to subtract 1 to get the index of the last value.
It looks like your function getFileExtension is designed to return the file extension of a given file. For example getFileExtension('image.gif') would return gif.
In the line (given that i is set to image.gif):
var filenameParts = i.split(".");
filenameParts will be an array, where image.gif has been split on the period. So filenameParts = ['image', 'gif'] where element zero is image and element one is gif. Remember that array indices are zero-based!
In the last line:
return filenameParts[filenameParts.length-1];
the function itself will return the last element in the filenameParts array (['image', 'gif']) which is gif. The part filenameParts.length-1 says get the length of the filenameParts array (which is 2), subtract 1 (which is 1), and return that element of the filenameParts array. So we return filenameParts[1] which is the last element of the array (remember, array indices are zero-based).
To get the last element of the array we could also have done
return filenameParts.pop();
because the pop() function returns the last element of an array.
var filenameParts = i.split('.') returns an array of made of the splitted elements of i
filenameParts[filenameParts.length-1];
select the last element of that array
I understand that the array.indexOf() function gives you the index of a particular element in an Array.
If an Element is found, Array.indexOf() returns the position of that element in the array.
If the Element is not found, Array.indexOf() would return -1 as an output.
However, I am trying to understand the output in the following scenario.
var arr = [2,3,4,5,7,5];
for(var i =0;i<arr.length;i++) {
console.log(arr.indexOf(i));
}
Output :
-1
-1
0
1
2
3
According to the Logic, When it finds 2 and 3 it should not return -1 in the console.
Going by the sequence of output i understand that the array index 0 starts at element 4 ?? Why is this happening?
I am just trying to understand what is going on?? Any Help would be highly appreciated.
-1 means the value was not found in the target array. The 0 means that the value was found at position 0 in the array and so on.
So when i = 2 in the loop it is finding the value 2 at position 0 in arr.
For reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf