What is the best way to find if an object is in an array?
This is the best way I know:
function include(arr, obj) { for (var i = 0; i < arr.length; i++) { if (arr[i] == obj) return true; } } console.log(include([1, 2, 3, 4], 3)); // true console.log(include([1, 2, 3, 4], 6)); // undefined
To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.
As of ECMAScript 2016 you can use includes()
arr.includes(obj);
If you want to support IE or other older browsers:
function include(arr,obj) { return (arr.indexOf(obj) != -1); }
EDIT: This will not work on IE6, 7 or 8 though. The best workaround is to define it yourself if it's not present:
Mozilla's (ECMA-262) version:
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; }; }
Daniel James's version:
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; }; }
roosteronacid's version:
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); } );
If you are using jQuery:
$.inArray(5 + 5, [ "8", "9", "10", 10 + "" ]);
For more information: http://api.jquery.com/jQuery.inArray/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With