Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 766
bier hier Avatar asked May 16 '17 04:05

bier hier


People also ask

How do you check if a string is present in an array JavaScript?

You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.

How do you check for Lodash strings?

isString() Method. The _. isString() method is used to find whether the given value is a string object or not. It returns True if the given value is a string.

How do I check if a value is an array in Lodash?

The Lodash _. isArray() method checks if the given value can be classified as an Array Value or not.

How do you check if an element is an array of strings?

Check if a String is contained in an Array using indexOf # We used the Array. indexOf method to check if the string two is contained in the array. If the string is not contained in the array, the indexOf method returns -1 , otherwise it returns the index of the first occurrence of the string in the array.


2 Answers

Should work

let go = "hello";

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

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

https://lodash.com/docs#includes

like image 100
Rick Calder Avatar answered Oct 12 '22 22:10

Rick Calder


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)
like image 4
brk Avatar answered Oct 12 '22 22:10

brk