scco
scco

Reputation: 149

explicit jquery indexOf()

lets say I have a string with ids from a database:

    string = "3, 4, 5, 8, 16, 2, 43"

and numbers from some checkbox values what I map into an array

    filter = ["35", "34"]

I want to compare if ALL numbers from the array are part of the string, so I tried something like this (what works a bit)

    if ( string.indexOf(filter) !== -1 )
    { console.log("numbers of filter are in string") }

but my problem is that of cause the 3 is in 34 - so indexOf is true. Any idea how I have to compare this "the right way" ?

Upvotes: 0

Views: 313

Answers (5)

Dmitry Grinko
Dmitry Grinko

Reputation: 15204

My example. Hope it helps

const str = "23, 4, 567, 7",
      firstArr = ["1", "3", "4"],
      secondArr = str.split(", ");

if(secondArr.filter(e => firstArr.indexOf(e) !== -1).length > 0) {
    console.log('str has some numbers from the firstArr');
}

Upvotes: 2

Sudhir Kumar
Sudhir Kumar

Reputation: 24

Please try this:

var string =  "3,4,5,8,16,2,43";
var filter = ["32", "42"];
var filter1 = ["3", "4"];

var stringArr = string.split(',');

var result = filter.every(function(val) { return stringArr.indexOf(val) >= 0; });
var result1 = filter1.every(function(val) { return stringArr.indexOf(val) >= 0; });

console.log(result);
console.log(result1);

Upvotes: 0

abney317
abney317

Reputation: 8492

Split the string to an array and check the values from there

string = "3, 4, 5, 8, 16, 2, 43";
stringarray = string.split(', ');


filter = ["35", "34"];
containsall = filter.every(elem => stringarray.indexOf(elem) > -1);
alert(containsall);


filter2 = ["3", "16"];
containsall = filter2.every(elem => stringarray.indexOf(elem) > -1);
alert(containsall);

Upvotes: 0

user4932805
user4932805

Reputation:

Use String.prototype.includes():

string.includes(filter)

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138235

You could easily add a whitespace in front:

const string = " 3, 4, 5, 8, 16, 2, 43",
    filters = ["35", "34"];

if(filters.every( filter => string.includes(" "+filter))){
  alert(" all found!");
}

Or you build a real array out of the string:

const string = "3, 4, 5, 8, 16, 2, 43",
    filters = ["35", "34"];

const ids = string.split(", ");

if(filters.every( filter => ids.includes(filter))) 
   alert(" all found!");

Upvotes: 0

Related Questions