What does 0 mean in indexOf? - javascript

While I am writing some JavaScript, I came across a new code "indexOf". After read another post I thought its behaviour is as shown below but it seems not true. Can someone kindly give me an explanation about "indexOf", please?
false = -1;
true = 0 and more?
I have tried to change -1 to 0 and more but then nothing happens. Just to have a better understanding about jquery/indexOf.
what I have now,
$(this).closest(row)[td_word.indexOf(keyword) !== -1 ? 'show' : 'hide']();
it search for match(es) of "keyword" from "td_word",
if it is not false (!== -1, thus true) display:visible;,
if it is not true (false) display:hide;.
Thanks in advance.

array.indexOf(element) returns the index of the element in the array. Read the official documentation as well.
It was designed to return -1 when the element doesn't exist, because 0 would mean that the element is in the 0th index (1st element).
Examples :
var array = ['a','b','c','d','e'];
array.indexOf('a') //0
array.indexOf('c') //2
array.indexOf('f') //-1, because it doesn't exist in array
From what I understand in your wording, I think that you think that indexOf is used to check if a certain element exists in an array. That is just a "side-effect" of indexOf but its actual usage is getting the index of an element in the array.

Related

javascript filter elements not found in second array

solved: requires explicit return statement for each filter. I thought the single boolean in each filter would be clear enough. by #adiga
I want to find the elements in one array (dcm) that are not found in a second array (vari). I want to match only two elements, vp (string type) and vd (date type). I've made sure there are some rows in dcm that meet the condition, but I'm getting no results.
Did I do up the code wrong? is there a better way to do this (.includes .contains .indexOf)?
var dcmm = dcm.filter(r=>{
vari.filter(rv=>{
rv[vp]+rv[vd] == r[dp]+r[dd]
}).length == 0
});
ps. sorrynotsorry to all the long variable name proponents out there. as well as the const-not-var proponents.
pps. this is google apps script not javascript, but I think the idea is the same.
Just in case, as it said #adiga you don't need return statements if you don't use {}.
Most likely this will work fine:
var dcmm = dcm.filter( r => vari.filter( rv => (rv[vp]+rv[vd] == r[dp]+r[dd]) ).length == 0 );

Sort array for object key that holds unique value

I have an array that looks like this:
var coll = [
{
prop1:true,
prop2:false,
id:"888399"
},
{
prop1:true,
prop2:true,
id:"/XS-555224"
},
{
prop1:false,
prop2:false,
id:"/DL-555444"
}
]
I want to sort the array so that the element with the ID that begins with "/DL" (for which there will always only be one) always starts at the top. How do I do that?
I don't feel like a custom sort will be the best choice because I don't have to compare elements against one another, I only have to find the one with the "/DL", slice it out, and insert it at the beginning of the array.
However, to do that, I'll still need to iterate over each element of the array to find the element and then perform a couple operations. So then I start thinking that I might as well just do the sort. The problem is how to write the correct condition to compare 2 items and checking the beginning of the ID string. So I figure that I can just simply test for the beginning of the String and return the value myself without comparison.
So I try this:
coll.sort(function(a,b){
var itemA = a.id;
var itemB = b.id;
if(itemA.lastIndexOf("/DL") === 0){
return 1;
}
});
But this comparison isn't working. What is wrong with my custom compare function? Thanks for any helpful tips.
Even though you are just looking for one record to move to the front you still need to check both parameters in the sort, it could be either one.
coll.sort(function(a,b) {
return a.id.indexOf('/DL') === 0 ? -1 : b.id.indexOf('/DL') === 0 ? 1 : 0;
});
Basically we want the '/DL' record to be the 'lowest' value in the array so it will show up first (sort orders things low to high). If a is lower we return negative, if b is lower we return positive. So when sorting if a is the /DL we need to return a negative. If b is the /DL we return a positive. So this expression in english is basically "Is a is our record? -1. If not, is b our record? 1. If neither then 0."
you can try this:
var orderedArr = coll.sort(function(val){
return !val.id.toString().startsWith('/DL');
});
[EDIT]
Once that you have user with IE, you can add this to make your life easier in the future:
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position) {
position = position || 0;
return this.indexOf(searchString, position) === position;
};
}
so you'll be able to use startsWith now and whenever you want.

JavaScript beginner, if a variable does not match to do something

Basically what I'm trying to do is write a greasemonkey script so that if a link on a page is not a link I have on an ignore list to just open the link, if it is on the list then reload the page after 5 seconds here is what I tried so far
var url1 = $("span.capsulelink a:eq(0) ").attr("href");
var ignoreList = ["example1.com","example2.com"]
if (url1 !== ignoreList) {
window.open(url1);
} else {
setTimeout(function() {
location.reload();
},5000);
}
I know it's the (url1 !== ignoreList) part I am having trouble with, I just can not seem to find the right expression for that. Like I do not know how to say if url1 is not on the ignoreList {do something}.
ignoreList.indexOf(url1) !== -1
This is another way of saying "is url contained in the ignoreList array?"
This is because the indexOf() method of Array returns the index of the element you're looking for, or -1 if the element doesn't exist.
To negate this, which is what you want to do, you write:
ignoreList.indexOf(url1) === -1
(i.e. is url1 not in ignoreList?)
This is a good question, because the answer really isn't intuitive.
When you're starting to learn javascript, some of the syntax patterns begin to look familiar.
But the javascript equivalent of PHP's
if (!in_array([ARRAY]));
simply isn't obvious at all - this is one syntax you just need to know.
Here is the javascript you're looking for:
if (ignoreList.indexOf(url1) !== -1) {
[RELOAD PAGE CODE HERE]
}
else {
[OPEN THE LINK CODE HERE]
}
Here's why it works:
ignoreList.indexOf([VALUE]) looks through the ignoreList array and searches through the array's items.
If one of those items is [VALUE], it returns the index of that item.
Importantly, if none of the items are [VALUE] it returns -1.
So, in order to establish that at least one of the items is [VALUE], you have to verify that the returned index definitely isn't -1.
Consequently the condition you need to check for is:
if (ignoreList.indexOf(url1) !== -1)

Best way to convert result of .indexOf to a Boolean using JavaScript or jQuery

I was wondering, say I had some thing like the following:
console.log(element.find('div').eq(3).text().indexOf('whatever'));
bearing in mind that element is defined and the console is logging a value of 32 (or anything that isn't -1) what would be the best way of converting the result into a Boolean so my console.log either outputs true or false
Thanks in advance.
The answer above will work, however if you are as nerdy as I, you will far prefer this:
console.log(~element.find('div').eq(3).text().indexOf('whatever'));
The obscure '~' operator in javascript performs the operation "value * -1 - 1", e.g. ~-2 === 1. The only use case I have ever had for this is in converting the "not found" -1 from ".indexOf()" into "0" (a falsey value in javascript), follow through and see it will convert an index found at position "0" to "-1", a truthy value.
tldr:
~[1,2,3].indexOf(0) // => 0
!!~[1,2,3].indexOf(0) // => false
~[1,2,3].indexOf(1) // => -1
!!~[1,2,3].indexOf(1) // => true
console.log(element.find('div').eq(3).text().indexOf('whatever') > -1);

Javascript indexOf() and Underscores

I am returning cookies through a Chrome Extension - one of the cookies.name is use_hitbox - so naturally I want to do:
if (cookie.name.indexOf("use_hitbox") > 0) {
alert("FOUND HITBOX COOKIE");
}
The Issue is:
cookie.name.indexOf("use") returns true
cookie.name.indexOf("hitbox") returns true
cookie.name.indexOf("use_hitbox") returns false
Any ideas?
Disclaimer:
This is for use on MY site, nothing malicious...!
EDIT: Cool, this works - but the underlying issue was Chrome Caching my Extensions file
indexOf() will return 0 if the match is at the beginning of the string. -1 indicates no match so try:
if (cookie.name.indexOf("use_hitbox") > -1)
Rather than parsing the returned index as boolean (which as pointed out, will mean an index of 0 parses as False), compare result != -1, which is the return value if the substring is not found.

Categories