My snippet looks something like this:
let go = "hello";
let col =["12","hello","14","15"];
let f = _.some(col,go);
I want to check whether the go value is present in col TRUE/FALSE. When I run this I get , f=false? How can I fix this or how to check the presence of a string in an array of strings (with lodash)?
3 Answers 3
Should work
let go = "hello";
let col =["12","hello","14","15"];
let f = _.includes(col,go);
Comments
With only javascript you can use indexOf. If it is present it will return the index of the element else -1
let go = "12";
let col = ["12", "hello", "14", "15"];
var isElemPresent = (col.indexOf(go) !== -1) ? true : false
console.log(isElemPresent)
13 Comments
indexOf will only return 1 for "hello". If you change go to anything else, this will return false. You should ideally use !== -1. You also need to watch out for type comparisons; indexOf performs a type-safe comparison so col.indexOf('12') will return 0 whereas col.indexOf(12) will return -1=== 1. This will return false for '12', '14' and '15'col.indexOf('12') returns 0 which means it certainly is present. If col contains "hello" at position #3, this will return false even though "hello" is certainly present. Naming your variable isPresent does not fit with what your code is doing. If you want it to be completely accurate, you should name it isHelloPresentAtExactlyTheSecondIndexIt seems that You misunderstood what the last arguments of _.some is. You can't use it as a value for equality test, but You need to make one yourself like this:
let f = _.some(col, function(go) {return go === "hello"});
And here is working Fiddle for You.
Or alternatively you can use es6 magic and call includes directly from your array like this
let go = "hello";
let col =["12","hello","14","15"];
alert(col.includes(go))