Related
This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
I need to determine if a value exists in an array.
I am using the following function:
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
The above function always returns false.
The array values and the function call is as below:
arrValues = ["Sam","Great", "Sample", "High"]
alert(arrValues.contains("Sam"));
jQuery has a utility function for this:
$.inArray(value, array)
Returns index of value in array. Returns -1 if array does not contain value.
See also How do I check if an array includes an object in JavaScript?
var contains = function(needle) {
// Per spec, the way to identify NaN is that it is not equal to itself
var findNaN = needle !== needle;
var indexOf;
if(!findNaN && typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(needle) {
var i = -1, index = -1;
for(i = 0; i < this.length; i++) {
var item = this[i];
if((findNaN && item !== item) || item === needle) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle) > -1;
};
You can use it like this:
var myArray = [0,1,2],
needle = 1,
index = contains.call(myArray, needle); // true
CodePen validation/usage
This is generally what the indexOf() method is for. You would say:
return arrValues.indexOf('Sam') > -1
Array.prototype.includes()
In ES2016, there is Array.prototype.includes().
The includes() method determines whether an array includes a certain element, returning true or false as appropriate.
Example
["Sam", "Great", "Sample", "High"].includes("Sam"); // true
Support
According to kangax and MDN, the following platforms are supported:
Chrome 47
Edge 14
Firefox 43
Opera 34
Safari 9
Node 6
Support can be expanded using Babel (using babel-polyfill) or core-js. MDN also provides a polyfill:
if (![].includes) {
Array.prototype.includes = function(searchElement /*, fromIndex*/ ) {
'use strict';
var O = Object(this);
var len = parseInt(O.length) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1]) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {k = 0;}
}
var currentElement;
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)) {
return true;
}
k++;
}
return false;
};
}
It's almost always safer to use a library like lodash simply because of all the issues with cross-browser compatibilities and efficiency.
Efficiency because you can be guaranteed that at any given time, a hugely popular library like underscore will have the most efficient method of accomplishing a utility function like this.
_.includes([1, 2, 3], 3); // returns true
If you're concerned about the bulk that's being added to your application by including the whole library, know that you can include functionality separately:
var includes = require('lodash/collections/includes');
NOTICE: With older versions of lodash, this was _.contains() rather than _.includes().
Since ECMAScript6, one can use Set:
var myArray = ['A', 'B', 'C'];
var mySet = new Set(myArray);
var hasB = mySet.has('B'); // true
var hasZ = mySet.has('Z'); // false
tl;dr
function includes(k) {
for(var i=0; i < this.length; i++){
if( this[i] === k || ( this[i] !== this[i] && k !== k ) ){
return true;
}
}
return false;
}
Example
function includes(k) {
for(var i=0; i < this.length; i++){
if( this[i] === k || ( this[i] !== this[i] && k !== k ) ){
return true;
}
}
return false;
}
function log(msg){
$('#out').append('<div>' + msg + '</div>');
}
var arr = [1, "2", NaN, true];
arr.includes = includes;
log('var arr = [1, "2", NaN, true];');
log('<br/>');
log('arr.includes(1): ' + arr.includes(1));
log('arr.includes(2): ' + arr.includes(2));
log('arr.includes("2"): ' + arr.includes("2"));
log('arr.includes(NaN): ' + arr.includes(NaN));
log('arr.includes(true): ' + arr.includes(true));
log('arr.includes(false): ' + arr.includes(false));
#out{
font-family:monospace;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=out></div>
Longer Answer
I know this question isn't really about whether or not to extend built-in objects, but the attempt of the OP and the comments on this answer highlight that debate. My comment from Feb 12, '13 cites an article that outlines this debate really well, however that link broke and I can't edit the original comment because too much time has passed, so I include it here.
If you're looking to extend the built-in Array object with a contains method, probably the best and most responsible way to do this would be to use this polyfill from MDN. (See also this section of the MDN article on Prototypical inheritance, which explains that "The only good reason for extending a built-in prototype is to backport the features of newer JavaScript engines; for example Array.forEach, etc.")
if (!Array.prototype.includes) {
Array.prototype.includes = function(searchElement /*, fromIndex*/ ) {
'use strict';
var O = Object(this);
var len = parseInt(O.length) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1]) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {k = 0;}
}
var currentElement;
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)) {
return true;
}
k++;
}
return false;
};
}
Don't want strict equality, or want to choose?
function includes(k, strict) {
strict = strict !== false; // default is true
// strict = !!strict; // default is false
for(var i=0; i < this.length; i++){
if( (this[i] === k && strict) ||
(this[i] == k && !strict) ||
(this[i] !== this[i] && k !== k)
) {
return true;
}
}
return false;
}
My little contribution:
function isInArray(array, search)
{
return array.indexOf(search) >= 0;
}
//usage
if(isInArray(my_array, "my_value"))
{
//...
}
If you have access to ECMA 5 you can use the some method.
MDN SOME Method Link
arrValues = ["Sam","Great", "Sample", "High"];
function namePresent(name){
return name === this.toString();
}
// Note:
// namePresent requires .toString() method to coerce primitive value
// i.e. String {0: "S", 1: "a", 2: "m", length: 3, [[PrimitiveValue]]: "Sam"}
// into
// "Sam"
arrValues.some(namePresent, 'Sam');
=> true;
If you have access to ECMA 6 you can use the includes method.
MDN INCLUDES Method Link
arrValues = ["Sam","Great", "Sample", "High"];
arrValues.includes('Sam');
=> true;
Given the implementation of indexOf for IE (as described by eyelidlessness):
Array.prototype.contains = function(obj) {
return this.indexOf(obj) > -1;
};
You can use _.indexOf method or if you don't want to include whole Underscore.js library in your app, you can have a look how they did it and extract necessary code.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i = 0, l = array.length;
if (isSorted) {
if (typeof isSorted == 'number') {
i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
} else {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
for (; i < l; i++) if (array[i] === item) return i;
return -1;
};
Another option would be to use Array.some (if available) in the following way:
Array.prototype.contains = function(obj) {
return this.some( function(e){ return e === obj } );
}
The anonymous function passed to Array.some will return true if and only if there is an element in the array that is identical to obj. Absent such an element, the function will not return true for any of the elements of the array, so Array.some will return false as well.
Wow, there are a lot of great answers to this question.
I didn't see one that takes a reduce approach so I'll add it in:
var searchForValue = 'pig';
var valueIsInArray = ['horse', 'cat', 'dog'].reduce(function(previous, current){
return previous || searchForValue === current ? true : false;
}, false);
console.log('The value "' + searchForValue + '" is in the array: ' + valueIsInArray);
Here's a fiddle of it in action.
The answer provided didn't work for me, but it gave me an idea:
Array.prototype.contains = function(obj)
{
return (this.join(',')).indexOf(obj) > -1;
}
It isn't perfect because items that are the same beyond the groupings could end up matching. Such as my example
var c=[];
var d=[];
function a()
{
var e = '1';
var f = '2';
c[0] = ['1','1'];
c[1] = ['2','2'];
c[2] = ['3','3'];
d[0] = [document.getElementById('g').value,document.getElementById('h').value];
document.getElementById('i').value = c.join(',');
document.getElementById('j').value = d.join(',');
document.getElementById('b').value = c.contains(d);
}
When I call this function with the 'g' and 'h' fields containing 1 and 2 respectively, it still finds it because the resulting string from the join is: 1,1,2,2,3,3
Since it is doubtful in my situation that I will come across this type of situation, I'm using this. I thought I would share incase someone else couldn't make the chosen answer work either.
Using array .map function that executes a function for every value in an array seems cleanest to me.
Ref: Array.prototype.map()
This method can work well both for simple arrays and for arrays of objects where you need to see if a key/value exists in an array of objects.
function inArray(myArray,myValue){
var inArray = false;
myArray.map(function(key){
if (key === myValue){
inArray=true;
}
});
return inArray;
};
var anArray = [2,4,6,8]
console.log(inArray(anArray, 8)); // returns true
console.log(inArray(anArray, 1)); // returns false
function inArrayOfObjects(myArray,myValue,objElement){
var inArray = false;
myArray.map(function(arrayObj){
if (arrayObj[objElement] === myValue) {
inArray=true;
}
});
return inArray;
};
var objArray = [{id:4,value:'foo'},{id:5,value:'bar'}]
console.log(inArrayOfObjects(objArray, 4, 'id')); // returns true
console.log(inArrayOfObjects(objArray, 'bar', 'value')); // returns true
console.log(inArrayOfObjects(objArray, 1, 'id')); // returns false
function setFound(){
var l = arr.length, textBox1 = document.getElementById("text1");
for(var i=0; i<l;i++)
{
if(arr[i]==searchele){
textBox1 .value = "Found";
return;
}
}
textBox1 .value = "Not Found";
return;
}
This program checks whether the given element is found or not. Id
text1 represents id of textbox and searchele represents element to be
searched (got fron user); if you want index, use i value
The simplest solution for a contains function, would be a function that looks like this :
var contains = function (haystack, needle) {
return !!~haystack.indexOf(needle);
}
Ideally, you wouldn't make this a stand-alone function, though, but part of a helper library :
var helper = {};
helper.array = {
contains : function (haystack, needle) {
return !!~haystack.indexOf(needle);
},
...
};
Now, if you happen to be one of those unlucky people who still needs to support IE<9 and thus can't rely on indexOf, you could use this polyfill, which I got from the MDN :
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
var len = o.length >>> 0;
if (len === 0) {
return -1;
}
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
if (n >= len) {
return -1;
}
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
while (k < len) {
if (k in o && o[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
I prefer simplicity:
var days = [1, 2, 3, 4, 5];
if ( 2 in days ) {console.log('weekday');}
If I have an array like this:
var array = [{ID:1,value:'test1'},
{ID:3,value:'test3'},
{ID:2,value:'test2'}]
I want to select an index by the ID.
i.e, I want to somehow select ID:3, and get {ID:3,value:'test3'}.
What is the fastest and most lightweight way to do this?
Use array.filter:
var results = array.filter(function(x) { return x.ID == 3 });
It returns an array, so to get the object itself, you'd need [0] (if you're sure the object exists):
var result = array.filter(function(x) { return x.ID == 3 })[0];
Or else some kind of helper function:
function getById(id) {
var results = array.filter(function(x) { return x.ID == id });
return (results.length > 0 ? results[0] : null);
}
var result = getById(3);
With lodash you can use find with pluck-style input:
_.find(result, {ID: 3})
Using filter is not the fastest way because filter will always iterate through the entire array even if element being search for is the first element. This can perform poorly on larger arrays.
If you are looking for fastest way, simply looping through until the element is found might be best option. Something like below.
var findElement = function (array, inputId) {
for (var i = array.length - 1; i >= 0; i--) {
if (array[i].ID === inputId) {
return array[i];
}
}
};
findElement(array, 3);
I would go for something like this:
function arrayObjectIndexOf(myArray, property, searchTerm) {
for (var i = 0, len = myArray.length; i < len; i++) {
if (myArray[i].property === searchTerm)
return myArray[i];
}
return -1;
}
In your case you should do:
arrayObjectIndexOf(array, id, 3);
var indexBy = function(array, property) {
var results = {};
(array||[]).forEach(function(object) {
results[object[property]] = object;
});
return results
};
which lets you var indexed = indexBy(array, "ID");
I think the title explains it well enough. I've got an array that has two values per object and I need to look up the object by one of those values then assign a third to it.
Here are the guts:
$slides.push({
img: el.attr('href'),
desc: el.attr('title').split('Photo #')[1]
});
Which builds an array as such:
Object
desc: 127
img: img/aaron1.jpg
Object
desc: 128
img: img/aaron2.jpg
I'd like to look up the desc value, then assign a third value of in: yes
$slides.findInArray('desc', '127').addValueToObject('in','yes')
http://jsfiddle.net/S3cpa/
var test = [
{
desc: 127,
img: 'img/aaron1.jpg',
},
{
desc: 128,
img: 'img/aaron2.jpg',
}
];
function getObjWhenPropertyEquals(prop, val)
{
for (var i = 0, l = test.length; i < l; i++) {
// check the obj has the property before comparing it
if (typeof test[i][prop] === 'undefined') continue;
// if the obj property equals our test value, return the obj
if (test[i][prop] === val) return test[i];
}
// didn't find an object with the property
return false;
}
// look up the obj and save it
var obj = getObjWhenPropertyEquals('desc', 127);
// set the new property if obj was found
obj.in = obj && 'yes';
easy way
for (var i = 0; i < $slides.length; i++)
{
if ($slides[i]["desc"] == "TEST_VALUE")
{
$slides[i]['in']='yes';
}
}
Another way
Array.prototype.findInArray =function(propName,value)
{
var res={};
if(propName && value)
{
for (var i=0; i<this.length; i++)
{
if(this[i][propName]==value)
{
res = this[i];
break;
}
}
}
return res;
}
Object.prototype.addValueToObject =function(prop,value)
{
this[prop]=value;
}
---Using It--
$slides.findInArray('desc', '127').addValueToObject('in','yes');
http://jsfiddle.net/s6ThK/
You need to run it through a for loop
// Loop through the array
for (var i = 0 ; i < $slides.length ; i++)
{
// Compare current item to the value you're looking for
if ($slides[i]["desc"] == myValue)
{
//do what you gotta do
$slides[i]["desc"] = newValue;
break;
}
}
With modern JS it can be simply done:
var obj = $slides.find(e => e.desc === '127');
if (obj) {
obj.in = 'yes';
}
For example, I have:
var Data = [
{ id_list: 1, name: 'Nick', token: '312312' },
{ id_list: 2, name: 'John', token: '123123' },
]
Then, I want to sort/reverse this object by name, for example. And then I want to get something like this:
var Data = [
{ id_list: 2, name: 'John', token: '123123' },
{ id_list: 1, name: 'Nick', token: '312312' },
]
And now I want to know the index of the object with property name='John' to get the value of the property token.
How do I solve the problem?
Since the sort part is already answered. I'm just going to propose another elegant way to get the indexOf of a property in your array
Your example is:
var Data = [
{id_list:1, name:'Nick', token:'312312'},
{id_list:2, name:'John', token:'123123'}
]
You can do:
var index = Data.map(function(e) { return e.name; }).indexOf('Nick');
var Data = [{
id_list: 1,
name: 'Nick',
token: '312312'
},
{
id_list: 2,
name: 'John',
token: '123123'
}
]
var index = Data.map(function(e) {
return e.name;
}).indexOf('Nick');
console.log(index)
Array.prototype.map is not available on Internet Explorer 7 or Internet Explorer 8. ES5 Compatibility
And here it is with ES6 and arrow syntax, which is even simpler:
const index = Data.map(e => e.name).indexOf('Nick');
If you're fine with using ES6, arrays now have the findIndex function. Which means you can do something like this:
const index = Data.findIndex(item => item.name === 'John');
As the other answers suggest, looping through the array is probably the best way. But I would put it in its own function, and make it a little more abstract:
function findWithAttr(array, attr, value) {
for(var i = 0; i < array.length; i += 1) {
if(array[i][attr] === value) {
return i;
}
}
return -1;
}
var Data = [
{id_list: 2, name: 'John', token: '123123'},
{id_list: 1, name: 'Nick', token: '312312'}
];
With this, not only can you find which one contains 'John', but you can find which contains the token '312312':
findWithAttr(Data, 'name', 'John'); // returns 0
findWithAttr(Data, 'token', '312312'); // returns 1
findWithAttr(Data, 'id_list', '10'); // returns -1
The function returns -1 when not found, so it follows the same construct as Array.prototype.indexOf().
If you're having issues with Internet Explorer, you could use the map() function which is supported from 9.0 onward:
var index = Data.map(item => item.name).indexOf("Nick");
var index = Data.findIndex(item => item.name == "John")
Which is a simplified version of:
var index = Data.findIndex(function(item){ return item.name == "John"})
From mozilla.org:
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.
Only way known to me is to loop through all array:
var index = -1;
for(var i=0; i<Data.length; i++)
if(Data[i].name === "John") {
index = i;
break;
}
Or case insensitive:
var index = -1;
for(var i=0; i<Data.length; i++)
if(Data[i].name.toLowerCase() === "john") {
index = i;
break;
}
On result variable index contain index of object or -1 if not found.
A prototypical way
(function(){
if (!Array.prototype.indexOfPropertyValue){
Array.prototype.indexOfPropertyValue = function(prop, value){
for (var index = 0; index < this.length; index++){
if (this[index][prop]){
if (this[index][prop] == value){
return index;
}
}
}
return -1;
}
}
})();
// Usage:
var Data = [
{id_list:1, name:'Nick', token:'312312'}, {id_list:2, name:'John', token:'123123'}];
Data.indexOfPropertyValue('name', 'John'); // Returns 1 (index of array);
Data.indexOfPropertyValue('name', 'Invalid name') // Returns -1 (no result);
var indexOfArray = Data.indexOfPropertyValue('name', 'John');
Data[indexOfArray] // Returns the desired object.
you can use filter method
const filteredData = data.filter(e => e.name !== 'john');
Just go through your array and find the position:
var i = 0;
for(var item in Data) {
if(Data[item].name == 'John')
break;
i++;
}
alert(i);
let indexOf = -1;
let theProperty = "value"
let searchFor = "something";
theArray.every(function (element, index) {
if (element[theProperty] === searchFor) {
indexOf = index;
return false;
}
return true;
});
collection.findIndex(item => item.value === 'smth') !== -1
You can use Array.sort using a custom function as a parameter to define your sorting mechanism.
In your example, it would give:
var Data = [
{id_list:1, name:'Nick',token:'312312'},{id_list:2,name:'John',token:'123123'}
]
Data.sort(function(a, b){
return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
});
alert("First name is : " + Data[0].name); // alerts 'John'
alert("Second name is : " + Data[1].name); // alerts 'Nick'
The sort function must return either -1 if a should come before b, 1 if a should come after b and 0 if both are equal. It's up to you to define the right logic in your sorting function to sort the array.
Missed the last part of your question where you want to know the index. You would have to loop through the array to find that as others have said.
This might be useful:
function showProps(obj, objName) {
var result = "";
for (var i in obj)
result += objName + "." + i + " = " + obj[i] + "\n";
return result;
}
I copied this from Working with objects.
Use a small workaround:
Create a new array with names as indexes. After that all searches will use indexes. So, only one loop. After that you don't need to loop through all elements!
var Data = [
{id_list:1, name:'Nick',token:'312312'},{id_list:2,name:'John',token:'123123'}
]
var searchArr = []
Data.forEach(function(one){
searchArr[one.name]=one;
})
console.log(searchArr['Nick'])
http://jsbin.com/xibala/1/edit
Live example.
I extended Chris Pickett's answer, because in my case I needed to search deeper than one attribute level:
function findWithAttr(array, attr, value) {
if (attr.indexOf('.') >= 0) {
var split = attr.split('.');
var attr1 = split[0];
var attr2 = split[1];
for(var i = 0; i < array.length; i += 1) {
if(array[i][attr1][attr2] === value) {
return i;
}
}
} else {
for(var i = 0; i < array.length; i += 1) {
if(array[i][attr] === value) {
return i;
}
}
};
};
You can pass 'attr1.attr2' into the function.
Use this:
Data.indexOf(_.find(Data, function(element) {
return element.name === 'John';
}));
It is assuming you are using Lodash or Underscore.js.
var fields = {
teste:
{
Acess:
{
Edit: true,
View: false
}
},
teste1:
{
Acess:
{
Edit: false,
View: false
}
}
};
console.log(find(fields,'teste'));
function find(fields,field) {
for(key in fields) {
if(key == field) {
return true;
}
}
return false;
}
If you have one Object with multiple objects inside, if you want know if some object are include on Master object, just use find(MasterObject, 'Object to Search'). This function will return the response if it exists or not (TRUE or FALSE). I hope to help with this - can see the example on JSFiddle.
If you want to get the value of the property token then you can also try this:
let data=[
{ id_list: 1, name: 'Nick', token: '312312' },
{ id_list: 2, name: 'John', token: '123123' },
]
let resultingToken = data[_.findKey(data,['name','John'])].token
where _.findKey is a Lodash function.
You can use findIndex in Lodash library.
Example:
var users = [
{ 'user': 'barney', 'active': false },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': true }
];
_.findIndex(users, function(o) { return o.user == 'barney'; });
// => 0
// The `_.matches` iteratee shorthand.
_.findIndex(users, { 'user': 'fred', 'active': false });
// => 1
// The `_.matchesProperty` iteratee shorthand.
_.findIndex(users, ['active', false]);
// => 0
// The `_.property` iteratee shorthand.
_.findIndex(users, 'active');
// => 2
Alternatively to German Attanasio Ruiz's answer, you can eliminate the second loop by using Array.reduce() instead of Array.map();
var Data = [
{ name: 'hypno7oad' }
]
var indexOfTarget = Data.reduce(function (indexOfTarget, element, currentIndex) {
return (element.name === 'hypno7oad') ? currentIndex : indexOfTarget;
}, -1);
Maybe the Object.keys, Object.entries, and Object.values methods might help.
Using Underscore.js:
var index = _.indexOf(_.pluck(item , 'name'), 'Nick');
This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
I need to determine if a value exists in an array.
I am using the following function:
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] == obj) {
return true;
}
}
return false;
}
The above function always returns false.
The array values and the function call is as below:
arrValues = ["Sam","Great", "Sample", "High"]
alert(arrValues.contains("Sam"));
jQuery has a utility function for this:
$.inArray(value, array)
Returns index of value in array. Returns -1 if array does not contain value.
See also How do I check if an array includes an object in JavaScript?
var contains = function(needle) {
// Per spec, the way to identify NaN is that it is not equal to itself
var findNaN = needle !== needle;
var indexOf;
if(!findNaN && typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(needle) {
var i = -1, index = -1;
for(i = 0; i < this.length; i++) {
var item = this[i];
if((findNaN && item !== item) || item === needle) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle) > -1;
};
You can use it like this:
var myArray = [0,1,2],
needle = 1,
index = contains.call(myArray, needle); // true
CodePen validation/usage
This is generally what the indexOf() method is for. You would say:
return arrValues.indexOf('Sam') > -1
Array.prototype.includes()
In ES2016, there is Array.prototype.includes().
The includes() method determines whether an array includes a certain element, returning true or false as appropriate.
Example
["Sam", "Great", "Sample", "High"].includes("Sam"); // true
Support
According to kangax and MDN, the following platforms are supported:
Chrome 47
Edge 14
Firefox 43
Opera 34
Safari 9
Node 6
Support can be expanded using Babel (using babel-polyfill) or core-js. MDN also provides a polyfill:
if (![].includes) {
Array.prototype.includes = function(searchElement /*, fromIndex*/ ) {
'use strict';
var O = Object(this);
var len = parseInt(O.length) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1]) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {k = 0;}
}
var currentElement;
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)) {
return true;
}
k++;
}
return false;
};
}
It's almost always safer to use a library like lodash simply because of all the issues with cross-browser compatibilities and efficiency.
Efficiency because you can be guaranteed that at any given time, a hugely popular library like underscore will have the most efficient method of accomplishing a utility function like this.
_.includes([1, 2, 3], 3); // returns true
If you're concerned about the bulk that's being added to your application by including the whole library, know that you can include functionality separately:
var includes = require('lodash/collections/includes');
NOTICE: With older versions of lodash, this was _.contains() rather than _.includes().
Since ECMAScript6, one can use Set:
var myArray = ['A', 'B', 'C'];
var mySet = new Set(myArray);
var hasB = mySet.has('B'); // true
var hasZ = mySet.has('Z'); // false
tl;dr
function includes(k) {
for(var i=0; i < this.length; i++){
if( this[i] === k || ( this[i] !== this[i] && k !== k ) ){
return true;
}
}
return false;
}
Example
function includes(k) {
for(var i=0; i < this.length; i++){
if( this[i] === k || ( this[i] !== this[i] && k !== k ) ){
return true;
}
}
return false;
}
function log(msg){
$('#out').append('<div>' + msg + '</div>');
}
var arr = [1, "2", NaN, true];
arr.includes = includes;
log('var arr = [1, "2", NaN, true];');
log('<br/>');
log('arr.includes(1): ' + arr.includes(1));
log('arr.includes(2): ' + arr.includes(2));
log('arr.includes("2"): ' + arr.includes("2"));
log('arr.includes(NaN): ' + arr.includes(NaN));
log('arr.includes(true): ' + arr.includes(true));
log('arr.includes(false): ' + arr.includes(false));
#out{
font-family:monospace;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=out></div>
Longer Answer
I know this question isn't really about whether or not to extend built-in objects, but the attempt of the OP and the comments on this answer highlight that debate. My comment from Feb 12, '13 cites an article that outlines this debate really well, however that link broke and I can't edit the original comment because too much time has passed, so I include it here.
If you're looking to extend the built-in Array object with a contains method, probably the best and most responsible way to do this would be to use this polyfill from MDN. (See also this section of the MDN article on Prototypical inheritance, which explains that "The only good reason for extending a built-in prototype is to backport the features of newer JavaScript engines; for example Array.forEach, etc.")
if (!Array.prototype.includes) {
Array.prototype.includes = function(searchElement /*, fromIndex*/ ) {
'use strict';
var O = Object(this);
var len = parseInt(O.length) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1]) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {k = 0;}
}
var currentElement;
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)) {
return true;
}
k++;
}
return false;
};
}
Don't want strict equality, or want to choose?
function includes(k, strict) {
strict = strict !== false; // default is true
// strict = !!strict; // default is false
for(var i=0; i < this.length; i++){
if( (this[i] === k && strict) ||
(this[i] == k && !strict) ||
(this[i] !== this[i] && k !== k)
) {
return true;
}
}
return false;
}
My little contribution:
function isInArray(array, search)
{
return array.indexOf(search) >= 0;
}
//usage
if(isInArray(my_array, "my_value"))
{
//...
}
If you have access to ECMA 5 you can use the some method.
MDN SOME Method Link
arrValues = ["Sam","Great", "Sample", "High"];
function namePresent(name){
return name === this.toString();
}
// Note:
// namePresent requires .toString() method to coerce primitive value
// i.e. String {0: "S", 1: "a", 2: "m", length: 3, [[PrimitiveValue]]: "Sam"}
// into
// "Sam"
arrValues.some(namePresent, 'Sam');
=> true;
If you have access to ECMA 6 you can use the includes method.
MDN INCLUDES Method Link
arrValues = ["Sam","Great", "Sample", "High"];
arrValues.includes('Sam');
=> true;
Given the implementation of indexOf for IE (as described by eyelidlessness):
Array.prototype.contains = function(obj) {
return this.indexOf(obj) > -1;
};
You can use _.indexOf method or if you don't want to include whole Underscore.js library in your app, you can have a look how they did it and extract necessary code.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i = 0, l = array.length;
if (isSorted) {
if (typeof isSorted == 'number') {
i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
} else {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
for (; i < l; i++) if (array[i] === item) return i;
return -1;
};
Another option would be to use Array.some (if available) in the following way:
Array.prototype.contains = function(obj) {
return this.some( function(e){ return e === obj } );
}
The anonymous function passed to Array.some will return true if and only if there is an element in the array that is identical to obj. Absent such an element, the function will not return true for any of the elements of the array, so Array.some will return false as well.
Wow, there are a lot of great answers to this question.
I didn't see one that takes a reduce approach so I'll add it in:
var searchForValue = 'pig';
var valueIsInArray = ['horse', 'cat', 'dog'].reduce(function(previous, current){
return previous || searchForValue === current ? true : false;
}, false);
console.log('The value "' + searchForValue + '" is in the array: ' + valueIsInArray);
Here's a fiddle of it in action.
The answer provided didn't work for me, but it gave me an idea:
Array.prototype.contains = function(obj)
{
return (this.join(',')).indexOf(obj) > -1;
}
It isn't perfect because items that are the same beyond the groupings could end up matching. Such as my example
var c=[];
var d=[];
function a()
{
var e = '1';
var f = '2';
c[0] = ['1','1'];
c[1] = ['2','2'];
c[2] = ['3','3'];
d[0] = [document.getElementById('g').value,document.getElementById('h').value];
document.getElementById('i').value = c.join(',');
document.getElementById('j').value = d.join(',');
document.getElementById('b').value = c.contains(d);
}
When I call this function with the 'g' and 'h' fields containing 1 and 2 respectively, it still finds it because the resulting string from the join is: 1,1,2,2,3,3
Since it is doubtful in my situation that I will come across this type of situation, I'm using this. I thought I would share incase someone else couldn't make the chosen answer work either.
Using array .map function that executes a function for every value in an array seems cleanest to me.
Ref: Array.prototype.map()
This method can work well both for simple arrays and for arrays of objects where you need to see if a key/value exists in an array of objects.
function inArray(myArray,myValue){
var inArray = false;
myArray.map(function(key){
if (key === myValue){
inArray=true;
}
});
return inArray;
};
var anArray = [2,4,6,8]
console.log(inArray(anArray, 8)); // returns true
console.log(inArray(anArray, 1)); // returns false
function inArrayOfObjects(myArray,myValue,objElement){
var inArray = false;
myArray.map(function(arrayObj){
if (arrayObj[objElement] === myValue) {
inArray=true;
}
});
return inArray;
};
var objArray = [{id:4,value:'foo'},{id:5,value:'bar'}]
console.log(inArrayOfObjects(objArray, 4, 'id')); // returns true
console.log(inArrayOfObjects(objArray, 'bar', 'value')); // returns true
console.log(inArrayOfObjects(objArray, 1, 'id')); // returns false
function setFound(){
var l = arr.length, textBox1 = document.getElementById("text1");
for(var i=0; i<l;i++)
{
if(arr[i]==searchele){
textBox1 .value = "Found";
return;
}
}
textBox1 .value = "Not Found";
return;
}
This program checks whether the given element is found or not. Id
text1 represents id of textbox and searchele represents element to be
searched (got fron user); if you want index, use i value
The simplest solution for a contains function, would be a function that looks like this :
var contains = function (haystack, needle) {
return !!~haystack.indexOf(needle);
}
Ideally, you wouldn't make this a stand-alone function, though, but part of a helper library :
var helper = {};
helper.array = {
contains : function (haystack, needle) {
return !!~haystack.indexOf(needle);
},
...
};
Now, if you happen to be one of those unlucky people who still needs to support IE<9 and thus can't rely on indexOf, you could use this polyfill, which I got from the MDN :
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
var len = o.length >>> 0;
if (len === 0) {
return -1;
}
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
if (n >= len) {
return -1;
}
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
while (k < len) {
if (k in o && o[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
I prefer simplicity:
var days = [1, 2, 3, 4, 5];
if ( 2 in days ) {console.log('weekday');}