8

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

asked May 16, 2017 at 4:16

3 Answers 3

30

Should work

let go = "hello";
let col =["12","hello","14","15"];
let f = _.includes(col,go);

https://lodash.com/docs#includes

answered May 16, 2017 at 4:22
Sign up to request clarification or add additional context in comments.

Comments

4

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)

answered May 16, 2017 at 4:20

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
@A.Lau the question is also tagged with javascript. Also nothing stop you from using javascript if you are using loadash. Check loadash library how inlcude function is implemented.
I will rather focus on answering some other question instead of clarifying. Thank you
@brk it's only downvoted because of === 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 isHelloPresentAtExactlyTheSecondIndex
|
0

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

answered May 16, 2017 at 4:35

1 Comment

this also searches by substring: let f = _.some(col, function(go) { return go.toLowerCase().indexOf("he".toLowerCase()) });

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.