Javascript elem in array

Best way to find if an item is in a JavaScript array? [duplicate]

2 things: 1.) ‘include’ is a really bad name for a function that does not modify the state of anything. It’s especially bad for a function that simply returns a boolean. 2.) You need to add «return(false);» before the end of the function.

In ES6 you can do something like arr.find(lamda function) , example: [1, 2, 3,4,5].find(x => x == 3). if element is found it is returned else undefined is returned

arr.some(element => element === obj); some is the bestway because when it finds an item and then break the loop.

8 Answers 8

As of ECMAScript 2016 you can use includes()

If you want to support IE or other older browsers:

EDIT: This will not work on IE6, 7 or 8 though. The best workaround is to define it yourself if it’s not present:

 if (!Array.prototype.indexOf) < Array.prototype.indexOf = function(searchElement /*, fromIndex */) < "use strict"; if (this === void 0 || this === null) throw new TypeError(); var t = Object(this); var len = t.length >>> 0; if (len === 0) return -1; var n = 0; if (arguments.length > 0) < n = Number(arguments[1]); if (n !== n) n = 0; else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) n = (n >0 || -1) * Math.floor(Math.abs(n)); > if (n >= len) return -1; var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) < if (k in t && t[k] === searchElement) return k; >return -1; >; > 
 if (!Array.prototype.indexOf) < Array.prototype.indexOf = function (obj, fromIndex) < if (fromIndex == null) < fromIndex = 0; >else if (fromIndex < 0) < fromIndex = Math.max(0, this.length + fromIndex); >for (var i = fromIndex, j = this.length; i < j; i++) < if (this[i] === obj) return i; >return -1; >; > 
 Array.prototype.hasObject = ( !Array.indexOf ? function (o) < var l = this.length + 1; while (l -= 1) < if (this[l - 1] === o) < return true; >> return false; > : function (o) < return (this.indexOf(o) !== -1); >); 

I’m curious as to why your version of the Mozilla function is so different from the website you’re linking to. Did you modify it yourself or is it just an old version or something?

Well, there’s my answer haha. I can’t tell if there’s an older version just by looking at the mozilla website so I wasn’t sure. Not that it matters, just a curiosity. In any case this was still helpful so you get an upvote 😉

@Vinko Vrsalovic Yes, it is a good solution, but you should hide embedded implementation indexOf() function which returns -1 with ~ operator: function include(arr,obj) < return !!(~arr.indexOf(obj)) ; >

but, since when is indexOf compatible with IE, because I found it is compatible with IE w3schools.com/jsref/jsref_indexof.asp

Note that «inArray» is a misnomer, because it doesn’t return boolean value — it returns index of first element found. So if you are checking if element exists you should use if (-1 != $.inArray(. )) . .

Читайте также:  Заголовок страницы

Helpful, but I don’t think it’s an appropriate answer here. The question is tagged «javascript» indicating «vanilla» in my opinion. 🙂

First, implement indexOf in JavaScript for browsers that don’t already have it. For example, see Erik Arvidsson’s array extras (also, the associated blog post). And then you can use indexOf without worrying about browser support. Here’s a slightly optimised version of his indexOf implementation:

if (!Array.prototype.indexOf) < Array.prototype.indexOf = function (obj, fromIndex) < if (fromIndex == null) < fromIndex = 0; >else if (fromIndex < 0) < fromIndex = Math.max(0, this.length + fromIndex); >for (var i = fromIndex, j = this.length; i < j; i++) < if (this[i] === obj) return i; >return -1; >; > 

It’s changed to store the length so that it doesn’t need to look it up every iteration. But the difference isn’t huge. A less general purpose function might be faster:

var include = Array.prototype.indexOf ? function(arr, obj) < return arr.indexOf(obj) !== -1; >: function(arr, obj) < for(var i = -1, j = arr.length; ++i < j;) if(arr[i] === obj) return true; return false; >; 

I prefer using the standard function and leaving this sort of micro-optimization for when it’s really needed. But if you’re keen on micro-optimization I adapted the benchmarks that roosterononacid linked to in the comments, to benchmark searching in arrays. They’re pretty crude though, a full investigation would test arrays with different types, different lengths and finding objects that occur in different places.

Источник

Array.prototype.includes()

Метод includes() определяет, содержит ли массив определённый элемент, возвращая в зависимости от этого true или false .

Интерактивный пример

Синтаксис

arr.includes(searchElement[fromIndex = 0])

Параметры

Позиция в массиве, с которой начинать поиск элемента searchElement . При отрицательных значениях поиск производится начиная с индекса array.length + fromIndex по возрастанию. Значение по умолчанию равно 0.

Возвращаемое значение

Примеры

[1, 2, 3].includes(2); // true [1, 2, 3].includes(4); // false [1, 2, 3].includes(3, 3); // false [1, 2, 3].includes(3, -1); // true [1, 2, NaN].includes(NaN); // true 

fromIndex больше или равен длине массива

Если fromIndex больше или равен длине массива, то возвращается false . При этом поиск не производится.

var arr = ['a', 'b', 'c']; arr.includes('c', 3); // false arr.includes('c', 100); // false 

Вычисленный индекс меньше нуля 0

Если fromIndex отрицательный, то вычисляется индекс, начиная с которого будет производиться поиск элемента searchElement . Если вычисленный индекс меньше нуля, то поиск будет производиться во всём массиве.

// длина массива равна 3 // fromIndex равен -100 // вычисленный индекс равен 3 + (-100) = -97 var arr = ['a', 'b', 'c']; arr.includes('a', -100); // true arr.includes('b', -100); // true arr.includes('c', -100); // true 

Использование includes() в качестве общих метода

includes() специально сделан общим. Он не требует, чтобы this являлся массивом, так что он может быть применён к другим типам объектов (например, к массивоподобным объектам). Пример ниже показывает использование метода includes() на объекте arguments.

(function()  console.log([].includes.call(arguments, 'a')); // true console.log([].includes.call(arguments, 'd')); // false >)('a','b','c'); 

Полифил

// https://tc39.github.io/ecma262/#sec-array.prototype.includes if (!Array.prototype.includes)  Object.defineProperty(Array.prototype, 'includes',  value: function(searchElement, fromIndex)  if (this == null)  throw new TypeError('"this" is null or not defined'); > // 1. Let O be ? ToObject(this value). var o = Object(this); // 2. Let len be ? ToLength(? Get(O, "length")). var len = o.length >>> 0; // 3. If len is 0, return false. if (len === 0)  return false; > // 4. Let n be ? ToInteger(fromIndex). // (If fromIndex is undefined, this step produces the value 0.) var n = fromIndex | 0; // 5. If n ≥ 0, then // a. Let k be n. // 6. Else n < 0,// a. Let k be len + n. // b. If k < 0, let k be 0.var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); function sameValueZero(x, y)  return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y)); > // 7. Repeat, while k < lenwhile (k  len)  // a. Let elementK be the result of ? Get(O, ! ToString(k)). // b. If SameValueZero(searchElement, elementK) is true, return true. if (sameValueZero(o[k], searchElement))  return true; > // c. Increase k by 1. k++; > // 8. Return false return false; > >); > 

Если требуется поддержка устаревших движков JavaScript, которые не поддерживают Object.defineProperty , то наилучшим решением будет вообще не делать полифил для методов Array.prototype , так как не получится сделать их неперечисляемыми.

Спецификации

Поддержка браузерами

BCD tables only load in the browser

Смотрите также

Источник

Array.prototype.find()

The find() method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

  • If you need the index of the found element in the array, use findIndex() .
  • If you need to find the index of a value, use indexOf() . (It’s similar to findIndex() , but checks each element for equality with the value instead of using a testing function.)
  • If you need to find if a value exists in an array, use includes() . Again, it checks each element for equality with the value instead of using a testing function.
  • If you need to find if any element satisfies the provided testing function, use some() .

Try it

Syntax

find(callbackFn) find(callbackFn, thisArg) 

Parameters

A function to execute for each element in the array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:

The current element being processed in the array.

The index of the current element being processed in the array.

The array find() was called upon.

A value to use as this when executing callbackFn . See iterative methods.

Return value

The first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.

Description

The find() method is an iterative method. It calls a provided callbackFn function once for each element in an array in ascending-index order, until callbackFn returns a truthy value. find() then returns that element and stops iterating through the array. If callbackFn never returns a truthy value, find() returns undefined .

callbackFn is invoked for every index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as undefined .

find() does not mutate the array on which it is called, but the function provided as callbackFn can. Note, however, that the length of the array is saved before the first invocation of callbackFn . Therefore:

  • callbackFn will not visit any elements added beyond the array’s initial length when the call to find() began.
  • Changes to already-visited indexes do not cause callbackFn to be invoked on them again.
  • If an existing, yet-unvisited element of the array is changed by callbackFn , its value passed to the callbackFn will be the value at the time that element gets visited. Deleted elements are visited as if they were undefined .

Warning: Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).

The find() method is generic. It only expects the this value to have a length property and integer-keyed properties.

Examples

Find an object in an array by one of its properties

const inventory = [  name: "apples", quantity: 2 >,  name: "bananas", quantity: 0 >,  name: "cherries", quantity: 5 >, ]; function isCherries(fruit)  return fruit.name === "cherries"; > console.log(inventory.find(isCherries)); // 

Using arrow function and destructuring

const inventory = [  name: "apples", quantity: 2 >,  name: "bananas", quantity: 0 >,  name: "cherries", quantity: 5 >, ]; const result = inventory.find(( name >) => name === "cherries"); console.log(result); // 

Find a prime number in an array

The following example finds an element in the array that is a prime number (or returns undefined if there is no prime number):

function isPrime(element, index, array)  let start = 2; while (start  Math.sqrt(element))  if (element % start++  1)  return false; > > return element > 1; > console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found console.log([4, 5, 8, 12].find(isPrime)); // 5 

Using find() on sparse arrays

Empty slots in sparse arrays are visited, and are treated the same as undefined .

// Declare array with no elements at indexes 2, 3, and 4 const array = [0, 1, , , , 5, 6]; // Shows all indexes, not just those with assigned values array.find((value, index) =>  console.log("Visited index", index, "with value", value); >); // Visited index 0 with value 0 // Visited index 1 with value 1 // Visited index 2 with value undefined // Visited index 3 with value undefined // Visited index 4 with value undefined // Visited index 5 with value 5 // Visited index 6 with value 6 // Shows all indexes, including deleted array.find((value, index) =>  // Delete element 5 on first iteration if (index === 0)  console.log("Deleting array[5] with value", array[5]); delete array[5]; > // Element 5 is still visited even though deleted console.log("Visited index", index, "with value", value); >); // Deleting array[5] with value 5 // Visited index 0 with value 0 // Visited index 1 with value 1 // Visited index 2 with value undefined // Visited index 3 with value undefined // Visited index 4 with value undefined // Visited index 5 with value undefined // Visited index 6 with value 6 

Calling find() on non-array objects

The find() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length .

const arrayLike =  length: 3, "-1": 0.1, // ignored by find() since -1 < 00: 2, 1: 7.3, 2: 4, >; console.log(Array.prototype.find.call(arrayLike, (x) => !Number.isInteger(x))); // 7.3 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

  • Polyfill of Array.prototype.find in core-js
  • Indexed collections
  • Array
  • Array.prototype.findIndex()
  • Array.prototype.findLast()
  • Array.prototype.findLastIndex()
  • Array.prototype.includes()
  • Array.prototype.filter()
  • Array.prototype.every()
  • Array.prototype.some()
  • TypedArray.prototype.find()

Found a content problem with this page?

This page was last modified on Jun 27, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Оцените статью