6

I need to check if a particular value exists in the main array.

Example:

var hideFilters = function() {
    var listCategoryId = ['1000014', '1000015', '1000016', '1000017', '1000018', '1000019', '1000021', '1000086'];

    var actualCategoryId = '1000018';

    if (actualCategoryId === listCategoryId) {
        console.log('is equal');
    } else {
        console.log('fuen... fuen...');
    }
};

hideFilters();
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
Rodrigo Dias
  • 147
  • 1
  • 1
  • 7

3 Answers3

6
if(listCategoryId.indexOf(actualCategoryId) != -1) {
  console.log('exists')
}
yBrodsky
  • 4,981
  • 3
  • 20
  • 31
2

If Array.prototype.indexOf() returns an index greater or equal 0, the array contains the specified element. Otherwise it will return -1:

var hideFilters = function() {
  var listCategoryId = ['1000014', '1000015', '1000016', '1000017', '1000018', '1000019', '1000021', '1000086'];

  var actualCategoryId = '1000018';

  if (listCategoryId.indexOf(actualCategoryId) > -1) {
    console.log('is equal');
  } else {
    console.log('fuen... fuen...');
  }
};

hideFilters();
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
1

You can use $.inArray

var listCategoryId = ['1000014', '1000015', '1000016', '1000017', '1000018', '1000019', '1000021', '1000086'];

var actualCategoryId = '1000018';

if ($.inArray(actualCategoryId, listCategoryId) != -1) {
  console.log('exists');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59
  • If you run that with `"1000014"` it would claim it doesn't exist because `$.inArray()` works like `.indexOf` – VLAZ Dec 02 '16 at 13:48
  • @vlaz fixed it.. thanks for pointing it out – Rajshekar Reddy Dec 02 '16 at 13:49
  • No worries. It caught me out, too (I started to write an answer but people posted before I was finished). I knew _of_ the `$.inArray` function, but (based on the name) I assumed it returns a boolean rather than an index...I blame jQuery for the confusion. – VLAZ Dec 02 '16 at 13:51
  • @vlaz true, the name sounds like it will return true or false, but what it returns is a index of the match. – Rajshekar Reddy Dec 02 '16 at 13:53