-2

say I have a set of string from which I have to search within a string that it contains any element or not.

var value = "01,05,04,02,00";
var temp = ["00", "01", "02", "03"];

I want to search existence of any item from temp in value, if any of the items from temp found in value, it should return true else false. what I am trying to do is opposite of searching a string in an array. How to achieve this in javascript?

Felipe Zavan
  • 1,654
  • 1
  • 14
  • 33
Piyush Kumar
  • 157
  • 1
  • 2
  • 14
  • 1
    Does this answer your question? [How do I check if an array includes a value in JavaScript?](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-a-value-in-javascript) – Felipe Zavan Jun 19 '20 at 11:15
  • 1
    `var temp="00","01","02","03";` is not valid Javascript. Did you mean `var temp=["00","01","02","03"];`? – connexo Jun 19 '20 at 11:23
  • @FelipeZavan , no. I am searching in a string, not in an array. – Piyush Kumar Jun 19 '20 at 12:05

3 Answers3

1

In modern Javascript you would use Array.prototype.some along with Array.prototype.includes for this:

const value = "01,05,04,02,00", arr = ["00", "01", "02", "03"];
let arrayItemInString = arr.some(el => value.split(',').includes(el));
console.log(arrayItemInString);

If instead you want to check if all array values are included in your string, use Array.prototype.every:

const value = "01,05,04,02,00", arr = ["00", "01", "02", "03"];
let arrayItemsInString = arr.every(el => value.split(',').includes(el));
console.log(arrayItemsInString);

Please note that for both solutions to work you need to convert your String to an array as well. The examples do this using value.split(',').

You could also use String.prototype.includes, but that would be alot less reliable as an array value of 01 would also be included in this string: 010:

const value = "010", arr = ["00", "01", "02", "03"];
let arrayItemInString = arr.some(el => value.includes(el));
console.log(arrayItemInString);
connexo
  • 53,704
  • 14
  • 91
  • 128
0

use this solution

function search(){
    var value= "01,05,04,02,00";
    var temp=["00","01","02","03"];
    for(var i=0;i<temp.length;i++){
        if(value.indexOf(temp[i])!==-1)
        {
        return true;
        }
    }
        return false;
  }
Mahamudul Hasan
  • 2,745
  • 2
  • 17
  • 26
0
var value= "01,05,04,02,00";
var temp=["00","01","02","03"];

const matchedItems = !!value.split(',').filter(item => temp.includes(item)).length

If value is an array like temp:

const matchedItems = !!value.filter(item => temp.includes(item)).length
thealpha93
  • 780
  • 4
  • 15