Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if string has at least 2 same elements from an array

I want to determine if string has at least 2 same elements from the array

const array = ["!", "?"];

const string1 = "!hello"; // should return false
const string2 = "!hello?"; // should return false
const string3 = "!hello!"; // should return true
const string4 = "hello ??"; // should return true
const string5 = "hello ?test? foo"; // should return true
const string6 = "hello ?test ?? foo"; // should return true

I'm not sure what is gonna be better: a regex or a function? Any would be fine.

I tried this:

const array = ["!", "?"];
const string = "test!";

array.every(ar => !string.includes(ar));

But it only detects if there at least 1 elements from array, not 2.

like image 264
Pleklo Avatar asked Oct 01 '19 10:10

Pleklo


People also ask

How do you find the matching string in an array?

Use indexOf as @Annie suggested. indexOf is used for finding substrings inside a given string. If there's no match, it returns -1 , otherwise it returns the starting index of the first match. If that index is 0 , it means the match was in the beginning.

How do you check if an element in an array is repeated?

To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.

How do you check if an array contains a value from another array?

Use the inbuilt ES6 function some() to iterate through each and every element of first array and to test the array. Use the inbuilt function includes() with second array to check if element exist in the first array or not. If element exist then return true else return false.


1 Answers

You can use Array#some and String#split to do it:

const check=(array,string)=>array.some(char=>(string.split(char).length-1)>=2)

const array = ["!", "?"];

console.log(check(array,"!hello"))
console.log(check(array,"!hello?"))
console.log(check(array,"!hello!"))
console.log(check(array,"hello ??"))
console.log(check(array,"hello ?test? foo"))
console.log(check(array, "hello ?test ?? foo"))

How does it work?

Let's split up (I mean to split() up)!

const check=(array,string)=>
  array.some(char=>
    (
      string.split(char)
      .length-1
    )>=2
  )
  • First, use Array#some, which tests that at least one element of the array should pass (i.e. either ? or !)
  • Split up the string by char, and count how many parts do we have
    • If we have n parts, it means that we have n-1 places where the char matches. (e.g. 2 | splits a string into 3 parts: a|b|c)
  • Finally, test whether we have 2 or more delimiters
like image 140
FZs Avatar answered Oct 19 '22 03:10

FZs