I have this array:
var str = "rrr";
var arr = ["ddd","rrr","ttt"];
I try to check If arr contains str. I try this:
var res = arr .find(str);
But on row above is not works any idea what I do wrong?
I have this array:
var str = "rrr";
var arr = ["ddd","rrr","ttt"];
I try to check If arr contains str. I try this:
var res = arr .find(str);
But on row above is not works any idea what I do wrong?
Try using indexOf: it's more widely supported and you can get the same results.
var index = arr.indexOf(str);
if(index != -1) {
console.log("found");
var element = arr[index]; //element found of your array
}
Your problem with find function it's probably due to it's compatibility:
As you can see, the chance you are using an incompatible browser it's not so far.
find (added in ES2015, aka "ES6") expects a function predicate. You're looking for indexOf:
var res = arr.indexOf(str);
...which finds things by comparing them with ===. You'll get -1 if it's not found, or its index if it is.
In a comment you've said:
no string exists I expect null if exists I expect true
...which seems a bit odd (I'd think you'd want true or false), but this will give you that:
var res = arr.indexOf(str) != -1 || null;
...because of JavaScript's curiously-powerful || operator (that's a post on my blog).
Just for completeness about find:
But you can use find; ES5 version (in case you're polyfilling but not transpiling):
var res = arr.find(function(entry) { return entry === str; });
or in ES2015:
let res = arr.find(entry => entry === str);
res will be null if it was not found, str if it was. But then, you already have str, so... :-) find is more useful when you're searching for, say, an object by a property value.
It's easy to use simple indexOf method. Just check the documentation.
var array = [2, 9, 9];
array.indexOf(2); // 0
array.indexOf(7); // -1
array.indexOf(9, 2); // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0
.find method of array prototype expects on input function callback, not string you are looking for.
var res = arr.find(function (element) {
return element === str;
};
Read more about it here.
Try using includes
var foo = ['aaa', 'bbb', 'ccc'];
console.log(foo.includes('aaa'));
console.log(foo.includes('ddd'));
output
true
false
Note: Array#includes wasn't added until ES2016 (in June 2016), so you need a polyfill/shim for even slightly out of date browsers (which is simple, there's one on MDN).