Как найти элемент в массиве jquery

jQuery.inArray( value, array [, fromIndex ] )Returns: Number

Description: Search for a specified value within an array and return its index (or -1 if not found).

  • version added: 1.2jQuery.inArray( value, array [, fromIndex ] )

    • value

      The value to search for.

    • array

      An array through which to search.

    • fromIndex

      The index of the array at which to begin the search. The default is 0, which will search the whole array.

The $.inArray() method is similar to JavaScript’s native .indexOf() method in that it returns -1 when it doesn’t find a match. If the first element within the array matches value, $.inArray() returns 0.

Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), to check for the presence of value within array, you need to check if it’s not equal to (or greater than) -1.

The comparison between values is strict. The following will return -1 (not found) because a number is being searched in an array of strings:

1

$.inArray( 5 + 5, [ "8", "9", "10", 10 + "" ] );

Example:

Report the index of some elements in the array.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

<title>jQuery.inArray demo</title>

<script src="https://code.jquery.com/jquery-3.7.0.js"></script>

<div>"John" found at <span></span></div>

<div>4 found at <span></span></div>

<div>"Karl" not found, so <span></span></div>

<div>"Pete" is in the array, but not at or after index 2, so <span></span></div>

var arr = [ 4, "Pete", 8, "John" ];

var $spans = $( "span" );

$spans.eq( 0 ).text( jQuery.inArray( "John", arr ) );

$spans.eq( 1 ).text( jQuery.inArray( 4, arr ) );

$spans.eq( 2 ).text( jQuery.inArray( "Karl", arr ) );

$spans.eq( 3 ).text( jQuery.inArray( "Pete", arr, 2 ) );

Demo:

Vanilla JS

To search in the array with Vanilla JS I would use the filter() method implemented into the Array prototype.

Note: For very large arrays you might want to consider refactoring those to async/await functions else it might slow down the user interface.

1. Using regular expressions (slower)

This is the most flexible approach as you could search for different patterns. You should be aware that the search term here is not a plain text, thus you have to escape most of non-alphanumeric chars according to the syntax. You should not pass unprocessed user input directly to the function, as it will not work as expected.

let a = ["foo","fool","cool","god"];
var term = 'oo'; // search term (regex pattern)
var search = new RegExp(term , 'i'); // prepare a regex object
let b = a.filter(item => search.test(item));
console.log(b); // ["foo","fool","cool"]

2. Using indexOf (faster)

In this particular case I would rather use indexOf() which is basically an equivalent of LIKE %term% but much faster than using regular expressions when working with large arrays.

It is a common case to do case-insensitive searches so make sure to use toLowerCase() for both the search terms and the array items. Otherwise remove it everywhere from the examples.

let a = ["foo","fool","cool","god"];
let term = 'oo';
let b = a.filter(item => item.toLowerCase().indexOf(term) > -1);
console.log(b); // ["foo","fool","cool"]

ES6 style (ES2015)

const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];

const filterItems = (needle, heystack) => {
  let query = needle.toLowerCase();
  return heystack.filter(item => item.toLowerCase().indexOf(query) >= 0);
}

console.log(filterItems('ap', fruits)); // ['apple', 'grapes']
console.log(filterItems('ang', fruits)); // ['mango', 'orange']

ES5 style

var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];

function filterItems(needle, heystack) {
  var query = needle.toLowerCase();
  return heystack.filter(function(item) {
      return item.toLowerCase().indexOf(query) >= 0;
  })
}

console.log(filterItems('ap', fruits)); // ['apple', 'grapes']
console.log(filterItems('ang', fruits)); // ['mango', 'orange']

This is the outdated answer

To search in the array with jQuery you might use jQuery.grep() or
jQuery.map(). Both return new array with filtered elements using a
callback function.

The fastest implementation (case insensitive) is using indexOf and
toUpperCase in the callback:

var search_term = 'oo'; // your search term as string
var search = search_term.toUpperCase();
var array = jQuery.grep(a, function(value) {
    return value.toUpperCase().indexOf(search) >= 0;
});

If you don’t need case insensitive search you can remove both .toUpperCase() to speed it up even further.

More flexible but much slower (good enough for small arrays) is to use
regular expression:

var search_term = "oo"; // search term
var search = new RegExp(search_term , "i");
var arr = jQuery.grep(a, function (value) {
    return search.test(value);
});

or

var search_term = "oo"; // search term
var search = new RegExp(search_term , "i");
var arr = jQuery.map(a, function (value) {
    return value.match(search) ? value : null;
});

Regular expressions allow you to make searches much more complex than %value%. However don’t use it if you don’t need it because it is
many times slower.

you should get an array arr with the matched elements

jQuery утилиты

Определение и применение

jQuery функция $.inArray() производит поиск переданного значения в массиве и возвращает его индекс при нахождении, или значение -1, если не найден.

Функция $.inArray() схожа с нативным методом JavaScript indexOf() объекта Array, который по аналогии возвращает -1, когда он не находит совпадение.


Обращаю Ваше внимание, что функция $.inArray() использует оператор строгого сравнения (===) при сравнении искомого элемента и элементов массива.


jQuery синтаксис:

Синтаксис 1.2:
$.inArray( value, arr );
$.inArray( value, arr, fromIndex )

value - Anything
arr - Array
fromIndex - Number

Добавлен в версии jQuery

1.2

Значения параметров

Параметр Описание
value Значение, которое требуется найти внутри массива. Обязательное значение.
arr Массив в котором происходит поиск необходимого значения.
fromIndex Индекс массива с которого начинается поиск. Значение по умолчанию равно 0 (поиск осуществляется по всему массиву). Допускается использование отрицательных значений, в этом случае индекс с которого будет произведено сравнение элементов будет расчитан по следующей формуле: length (длина массива) + fromIndex. Необязательный аргумент.

Пример использования

const arr = [1, 2, 3, "a", "b", "c"]; // инициализируем переменную, содержащую массив
$.inArray( "a", arr );  // возвращаемое значение 3
$.inArray( "d", arr ); // возвращаемое значение -1 (значение не найдено в массиве)
$.inArray( "b", arr, 3 ); // возвращаемое значение 4
$.inArray( 2, arr, 2 ); // возвращаемое значение -1 (значение не найдено в массиве)
$.inArray( 1, arr, -6 ); // возвращаемое значение 0
$.inArray( 1, arr, -5 ); // возвращаемое значение -1 (значение не найдено в массиве)

В следующем примере мы рассмотрим с Вами как продолжить поиск искомого элемента в массиве после первого и последующих совпадений, вплоть до конца массива. Это позволит нам сравнить все элементы массива по определенному индексу на предмет наличия искомого элемента:

let indexes = []; // инициализируем переменную, содержащую пустой массив
const myArray = ['z', 'v', 'z', 'v', 'z', 'v']; // инициализируем переменную, содержащую массив строковых значений по которому будет произведен поиск
const searchElement = 'z'; // инициализируем строковую переменную (значение переменной будем искать внутри массива myArray)
let index = $.inArray(searchElement, myArray); // инициализируем переменную, содержащую индекс первого искомого элемента (значение переменной searchElement) внутри массива myArray

while ( index != -1 ) { // пока значение переменной index не будет равно -1
  indexes.push( index ); // с использованием метода push() добавляем в переменную indexes значение переменной index
  index = $.inArray(searchElement, myArray, index + 1); // изменяем значение переменной путем поиска необходимого элемента далее в массиве (если найден - индекс элемента, если нет то -1)
}

console.log( indexes ); // переменная содержит значение [0, 2, 4]

Обратите внимание на то, что если вы ищете внутри массива NaN (Not a number – не число), независимо от наличия этого значения в массиве возвращаемое значение будет -1. Это поведение метода учтено в нативном методе includes()ECMAScript 2016, добавленном в ECMAScript 2016, он решает подобную задачу, но возвращает логическое значение:

const arr = [NaN];  // инициализируем переменную, содержащую одно значение NaN

arr.indexOf( NaN ); // возвращаемое значение -1 (элемент не найден)
$.inArray( NaN, arr );  // возвращаемое значение -1 (элемент не найден)

arr.includes( NaN ); // возвращаемое значение true (элемент найден)

jQuery утилиты

Try jQuery.inArray()

Here is a jsfiddle link using the same code : http://jsfiddle.net/yrshaikh/SUKn2/

The $.inArray() method is similar to JavaScript’s native .indexOf() method in that it returns -1 when it doesn’t find a match. If the first element within the array matches value, $.inArray() returns 0

Example Code :

<html>
   <head>
      <style>
         div { color:blue; }
         span { color:red; }
  </style>
      <script src="http://code.jquery.com/jquery-latest.js"></script>
   </head>
   <body>    
      <div>"John" found at <span></span></div>
      <div>4 found at <span></span></div>
      <div>"Karl" not found, so <span></span></div>
      <div>
         "Pete" is in the array, but not at or after index 2, so <span></span>
      </div>
      <script>
         var arr = [ 4, "Pete", 8, "John" ];
         var $spans = $("span");
         $spans.eq(0).text(jQuery.inArray("John", arr));
         $spans.eq(1).text(jQuery.inArray(4, arr));
         $spans.eq(2).text(jQuery.inArray("Karl", arr));
         $spans.eq(3).text(jQuery.inArray("Pete", arr, 2));
      </script>  
   </body>
</html>

Output:

"John" found at 3
4 found at 0
"Karl" not found, so -1
"Pete" is in the array, but not at or after index 2, so -1

Содержание:

  • jQuery.inArray( value, array [, fromIndex ] )

    • jQuery.inArray( value, array [, fromIndex ] )
  • Обсуждение
  • Примеры

jQuery.inArray( value, array [, fromIndex ] )Возвращает: Number

Описание: Ищет заданный элемент в массиве. Возвращает индекс этого элемента или -1 в случае его отсутствия.

  • Добавлен в версии: 1.2jQuery.inArray( value, array [, fromIndex ] )

    • value

      The value to search for.

    • array

      An array through which to search.

    • fromIndex

      The index of the array at which to begin the search. The default is 0, which will search the whole array.

The $.inArray() method is similar to JavaScript’s native .indexOf() method in that it returns -1 when it doesn’t find a match. If the first element within the array matches value, $.inArray() returns 0.

Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), to check for the presence of value within array, you need to check if it’s not equal to (or greater than) -1.

The comparison between values is strict. The following will return -1 (not found) because a number is being searched in an array of strings:

1

$.inArray( 5 + 5, [ "8", "9", "10", 10 + "" ] );

Примеры использования

Добавить комментарий