简体   繁体   中英

Ramda, check(filter) if array of strings contains substring

For example I have an array:

let data = [ 'abc', 'dfgx', 'dfgxabc', 'xyzz' ]

And test substring:

const searchStr = 'abc'

I need another array that contains any matched values from data array.

let result = ['abc', 'dfgxabc']

In my task I getting a string from keyboard input, it can contain at least 3 characters and more. So it something like live search.

I'm trying to use Ramda:

const data = [ 'abc', 'dfg', 'xyz' ]

const searchStr = 'abc'

const filtered = R.filter(R.match(new RegExp(searchStr, 'i')), data)

You can do it with native js with the help of Array.prototype.filter and RegExp.prototype.test

 const data = [ 'abc', 'dfgx', 'dfgxabc', 'xyzz' ]; const searchStr = 'abc'; const filtered = data.filter(s => new RegExp(searchStr, 'ig').test(s)); console.log(filtered);

In the interest of answering the question directly,

const data = [ 'abc', 'dfgx', 'dfgxabc', 'xyzz' ];

const findABC = filter(test(/abc/));

findABC(data)

is the equivalent using Ramda. Take a look in the REPL .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM