jQuery check if in array


#1

Hi,

I have an array:

["Test page 03", "Test page 03", Test page 04]

I would like to check if “Test Page 03” is present several times in the array.
Can’t use “unique()” function of jQuery since it remove duplicates, I don’t want to remove it, I just want to check it to pass an if statement.

“jQuery.inArray()” isn’t really doing what I’m looking for.

Anyone an idea?

Thanks!


#2

You could just create a nested for loop, that way you can count exactly how many times each item in your array is duplicated…


#3
Yaeko said

Hi,

I have an array:

["Test page 03", "Test page 03", Test page 04]

I would like to check if “Test Page 03” is present several times in the array.
Can’t use “unique()” function of jQuery since it remove duplicates, I don’t want to remove it, I just want to check it to pass an if statement.

“jQuery.inArray()” isn’t really doing what I’m looking for.

Anyone an idea?

Thanks!


var present = false;
var present_count = 0;

for(var i in array) 
{

     if (array[i] == "Test Page 03") 
     {

          present_count += 1;

     }
 
}

if (present_count > 1) 
{

     present = true;

}


#4
ThemeProvince said
Yaeko said

Hi,

I have an array:

["Test page 03", "Test page 03", Test page 04]

I would like to check if “Test Page 03” is present several times in the array.
Can’t use “unique()” function of jQuery since it remove duplicates, I don’t want to remove it, I just want to check it to pass an if statement.

“jQuery.inArray()” isn’t really doing what I’m looking for.

Anyone an idea?

Thanks!


var present = false;
var present_count = 0;

for(var i in array) 
{

     if (array[i] == "Test Page 03") 
     {

          present_count += 1;

     }
 
}

if (present_count > 1) 
{

     present = true;

}

Okay, it’s working in this kind of way.
Thanks!


#5
var ar = ["a", "a", "b", "c"];

var duplicate = ar.indexOf("a") !== ar.lastIndexOf("a");

console.log(duplicate); // true