bier hier
bier hier

Reputation: 22540

How to check whether string is present in array with lodash js?

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)?

Upvotes: 8

Views: 25818

Answers (3)

JSEvgeny
JSEvgeny

Reputation: 2750

It 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))

Upvotes: 0

brk
brk

Reputation: 50291

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)

Upvotes: 4

Rick Calder
Rick Calder

Reputation: 18705

Should work

let go = "hello";

let col =["12","hello","14","15"];

let f = _.includes(col,go);

https://lodash.com/docs#includes

Upvotes: 30

Related Questions