Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an item exists in the array [duplicate]

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();
like image 936
Rodrigo Dias Avatar asked Dec 02 '16 13:12

Rodrigo Dias


2 Answers

if(listCategoryId.indexOf(actualCategoryId) != -1) {
  console.log('exists')
}
like image 167
yBrodsky Avatar answered Sep 25 '22 17:09

yBrodsky


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();
like image 44
TimoStaudinger Avatar answered Sep 25 '22 17:09

TimoStaudinger