Quantcast
Channel: How do I check if an array includes a value in JavaScript? - Stack Overflow
Browsing latest articles
Browse All 66 View Live

Answer by Shiva for How do I check if an array includes a value in JavaScript?

Simple solution for this requirement is using find() If you're having array of objects like below, var users = [{id: "101", name: "Choose one..."}, {id: "102", name: "shilpa"}, {id: "103", name:...

View Article


Answer by Sumer for How do I check if an array includes a value in JavaScript?

Surprised that this question still doesn't have latest syntax added, adding my 2 cents. Let's say we have array of Objects arrObj and we want to search obj in it. Array.prototype.indexOf -> (returns...

View Article


Answer by Sanjay Magar for How do I check if an array includes a value in...

function countArray(originalArray) { var compressed = []; // make a copy of the input array var copyArray = originalArray.slice(0); // first loop goes over every element for (var i = 0; i <...

View Article

Answer by Nitesh Ranjan for How do I check if an array includes a value in...

In Addition to what others said, if you don't have a reference of the object which you want to search in the array, then you can do something like this. let array = [1, 2, 3, 4, {"key": "value"}];...

View Article

Answer by ngCourse for How do I check if an array includes a value in...

Simple solution : ES6 Features "includes" method let arr = [1, 2, 3, 2, 3, 2, 3, 4]; arr.includes(2) // true arr.includes(93) // false

View Article


Answer by Durgpal Singh for How do I check if an array includes a value in...

I recommended to use underscore library because its return the value and its supported for all browsers. underscorejs var findValue = _.find(array, function(item) { return item.id == obj.id; });

View Article

Answer by Neil Girardi for How do I check if an array includes a value in...

If you're working with ES6 You can use a set: function arrayHas( array, element ) { const s = new Set(array); return s.has(element) } This should be more performant than just about any other method

View Article

Answer by Mitul Panchal for How do I check if an array includes a value in...

It has one parameter: an array numbers of objects. Each object in the array has two integer properties denoted by x and y. The function must return a count of all such objects in the array that satisfy...

View Article


Answer by Jeeva for How do I check if an array includes a value in JavaScript?

I was working on a project that I needed a functionality like python set which removes all duplicates values and returns a new list, so I wrote this function maybe useful to someone function set(arr) {...

View Article


Answer by Krishna Ganeriwal for How do I check if an array includes a value...

Either use Array.indexOf(Object). With ECMA 7 one can use the Array.includes(Object). With ECMA 6 you can use Array.find(FunctionName) where FunctionName is a user defined function to search for the...

View Article

Answer by KRRySS for How do I check if an array includes a value in JavaScript?

Using idnexOf() 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)); }

View Article

Answer by Alireza for How do I check if an array includes a value in JavaScript?

OK, you can just optimise your code to get the result! There are many ways to do this which are cleaner and better, but I just wanted to get your pattern and apply to that using JSON.stringify, just...

View Article

Answer by Maxime Helen for How do I check if an array includes a value in...

Or this solution: Array.prototype.includes = function (object) { return !!+~this.indexOf(object); };

View Article


Answer by Igor Barbashin for How do I check if an array includes a value in...

Solution that works in all modern browsers: function contains(arr, obj) { const stringifiedObj = JSON.stringify(obj); // Cache our object to not call `JSON.stringify` on every iteration return...

View Article

Answer by user2724028 for How do I check if an array includes a value in...

You can also use this trick: var arrayContains = function(object) { return (serverList.filter(function(currentObject) { if (currentObject === object) { return currentObject } else { return false; }...

View Article


Answer by sqram for How do I check if an array includes a value in JavaScript?

By no means the best, but I was just getting creative and adding to the repertoire. Do not use this Object.defineProperty(Array.prototype, 'exists', { value: function(element, index) { var index =...

View Article

Answer by rlib for How do I check if an array includes a value in JavaScript?

One can use Set that has the method "has()": function contains(arr, obj) { var proxy = new Set(arr); if (proxy.has(obj)) return true; else return false; } var arr = ['Happy', 'New', 'Year'];...

View Article


Answer by cocco for How do I check if an array includes a value in JavaScript?

A hopefully faster bidirectional indexOf / lastIndexOf alternative 2015 While the new method includes is very nice, the support is basically zero for now. It's long time that I was thinking of way to...

View Article

Answer by AlonL for How do I check if an array includes a value in JavaScript?

One-liner: function contains(arr, x) { return arr.filter(function(elem) { return elem == x }).length > 0; }

View Article

Answer by Oriol for How do I check if an array includes a value in JavaScript?

ECMAScript 7 introduces Array.prototype.includes. It can be used like this: [1, 2, 3].includes(2); // true [1, 2, 3].includes(4); // false It also accepts an optional second argument fromIndex: [1, 2,...

View Article

Answer by Michael for How do I check if an array includes a value in JavaScript?

The top answers assume primitive types but if you want to find out if an array contains an object with some trait, Array.prototype.some() is a very elegant solution: const items = [ {a: '1'}, {a: '2'},...

View Article


Answer by Pradeep Mahdevu for How do I check if an array includes a value in...

ECMAScript 6 has an elegant proposal on find. The find method executes the callback function once for each element present in the array until it finds one where callback returns a true value. If such...

View Article


Answer by Mina Gabriel for How do I check if an array includes a value in...

Use: var myArray = ['yellow', 'orange', 'red'] ; alert(!!~myArray.indexOf('red')); //true Demo To know exactly what the tilde ~ do at this point, refer to this question What does a tilde do when it...

View Article

Answer by Matías Cánepa for How do I check if an array includes a value in...

Use: function isInArray(array, search) { return array.indexOf(search) >= 0; } // Usage if(isInArray(my_array, "my_value")) { //... }

View Article

Answer by ninjagecko for How do I check if an array includes a value in...

While array.indexOf(x)!=-1 is the most concise way to do this (and has been supported by non-Internet Explorer browsers for over decade...), it is not O(1), but rather O(N), which is terrible. If your...

View Article


Answer by william malo for How do I check if an array includes a value in...

b is the value, and a is the array. It returns true or false: function(a, b) { return a.indexOf(b) != -1 }

View Article

Answer by Carlos A for How do I check if an array includes a value in...

Use: Array.prototype.contains = function(x){ var retVal = -1; // x is a primitive type if(["string","number"].indexOf(typeof x)>=0 ){ retVal = this.indexOf(x);} // x is a function else if(typeof x...

View Article

Answer by Ekim for How do I check if an array includes a value in JavaScript?

Literally: (using Firefox v3.6, with for-in caveats as previously noted (HOWEVER the use below might endorse for-in for this very purpose! That is, enumerating array elements that ACTUALLY exist via a...

View Article

Answer by Dennis Allen for How do I check if an array includes a value in...

Just another option // usage: if ( ['a','b','c','d'].contains('b') ) { ... } Array.prototype.contains = function(value){ for (var key in this) if (this[key] === value) return true; return false; } Be...

View Article



Answer by MattMcKnight for How do I check if an array includes a value in...

Thinking out of the box for a second, if you are making this call many many times, it is vastly more efficient to use an associative array a Map to do lookups using a hash function....

View Article

Answer by codeape for How do I check if an array includes a value in JavaScript?

Current browsers have Array#includes, which does exactly that, is widely supported, and has a polyfill for older browsers. > ['joe', 'jane', 'mary'].includes('jane'); true You can also use...

View Article

Answer by Már Örlygsson for How do I check if an array includes a value in...

Here's a JavaScript 1.6 compatible implementation of Array.indexOf: if (!Array.indexOf) { Array.indexOf = [].indexOf ? function(arr, obj, from) { return arr.indexOf(obj, from); } : function(arr, obj,...

View Article

Answer by Damir Zekić for How do I check if an array includes a value in...

Update from 2019: This answer is from 2008 (11 years old!) and is not relevant for modern JS usage. The promised performance improvement was based on a benchmark done in browsers of that time. It might...

View Article


How do I check if an array includes a value in JavaScript?

What is the most concise and efficient way to find out if a JavaScript array contains a value? This is the only way I know to do it: function contains(a, obj) { for (var i = 0; i < a.length; i++) {...

View Article

Answer by Mamunur Rashid for How do I check if an array includes a value in...

Adding a unique item to a another listsearchResults: [ { name: 'Hello', artist: 'Selana', album: 'Riga', id: 1, }, { name: 'Hello;s', artist: 'Selana G', album: 'Riga1', id: 2, }, { name: 'Hello2',...

View Article

Answer by Majedur Rahaman for How do I check if an array includes a value in...

Object.keys for getting all property names of the object and filter all values that exact or partial match with specified string.function filterByValue(array, string) { return array.filter(o =>...

View Article


Image may be NSFW.
Clik here to view.

Answer by Kamil Kiełczewski for How do I check if an array includes a value...

PerformanceToday 2019.01.07 I perform tests on MacOs HighSierra 10.13.6 on Chrome v78.0.0, Safari v13.0.4 and Firefox v71.0.0 for 15 chosen solutions. Conclusionssolutions based on JSON, Set and...

View Article


Answer by Riwaj Chalise for How do I check if an array includes a value in...

Use indexOf()You can use the indexOf() method to check whether a given value or element exists in an array or not. The indexOf() method returns the index of the element inside the array if it is found,...

View Article

Answer by Md. Harun Or Rashid for How do I check if an array includes a value...

This may be a detailed and easy solution.//plain arrayvar arr = ['a', 'b', 'c'];var check = arr.includes('a');console.log(check); //returns trueif (check){ // value exists in array //write some...

View Article

Answer by da coconut for How do I check if an array includes a value in...

use Array.prototype.includes for example: const fruits = ['coconut', 'banana', 'apple']const doesFruitsHaveCoconut = fruits.includes('coconut')// trueconsole.log(doesFruitsHaveCoconut)maybe read this...

View Article

Answer by Msilucifer for How do I check if an array includes a value in...

You can use findIndex function to check if an array has a specific value.arrObj.findIndex(obj => obj === comparedValue) !== -1;Returns true if arrObj contains comparedValue, false otherwise.

View Article


Answer by francis for How do I check if an array includes a value in JavaScript?

Using RegExp:console.log(new RegExp('26242').test(['23525', '26242', '25272'].join(''))) // true

View Article

Answer by Ran Turner for How do I check if an array includes a value in...

There are a couple of options for doing that including includes, some, find, findIndex.const array = [1, 2, 3, 4, 5, 6, 7];console.log(array.includes(3));//includes() determines whether an array...

View Article


Image may be NSFW.
Clik here to view.

Answer by Med Aziz CHETOUI for How do I check if an array includes a value in...

The best default method to check if value exist in array JavaScript is some()Array.prototype.some()The some() method tests whether at least one element in the array passes the test implemented by the...

View Article

Answer by Tiago Bértolo for How do I check if an array includes a value in...

The fastest method in Javascript to find if an array contains a value is this:function existsInArrayForIgnoreDataType(arr, targetElem) { for (let i = 0; i < arr.length; i++) { if (arr[i] ==...

View Article


Image may be NSFW.
Clik here to view.

Answer by Rohìt Jíndal for How do I check if an array includes a value in...

If you're just trying to check whether a value is included in a collection, It would be more appropriate to use a Set, As Arrays can have duplicate values whereas Sets cannot. Also, Replacing...

View Article

Answer by Aurobindo Bhuyan for How do I check if an array includes a value in...

There are several ways to find out.You can use inbuilt Array methods. The most prominently used is Array find method.const arr1 = [1, 2, 3, 4, 5]const result = arr1.find(ele => ele ===...

View Article

Answer by Shakil Abdus Shohid for How do I check if an array includes a value...

Complexity O(n/2)You can use any library function but I did it using core JavaScript. We search first search the element in the middle if we get return true, else we search the element in array from...

View Article

Answer by perona chan for How do I check if an array includes a value in...

see lots of resultsconst array = [1, 2, 3, 4, 2]console.log( array.indexOf(2), // 1 array.filter(e => e == 2), // [ 2, 2 ] array.includes(2), // true array.find(e => e == 2) // 2)// view does not...

View Article


Answer by Zia for How do I check if an array includes a value in JavaScript?

This is how you can do.const arr = [1, 2, 3, 4, 5];console.log(arr.includes(3)); // trueconsole.log(arr.includes(6)); // false

View Article

Browsing latest articles
Browse All 66 View Live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>