The function I am using now to check this is the following:
function inArray(needle,haystack) { var count=haystack.length; for(var i=0;i<count;i++) { if(haystack[i]===needle){return true;} } return false; }
It works. What I'm looking for is whether there is a better way of doing this.
The standard way to find duplicate elements from an array is by using the HashSet data structure. If you remember, Set abstract data type doesn't allow duplicates. You can take advantage of this property to filter duplicate elements.
Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.
One more way to detect duplication in the java array is adding every element of the array into HashSet which is a Set implementation. Since the add(Object obj) method of Set returns false if Set already contains an element to be added, it can be used to find out if the array contains duplicates in Java or not.
Using Set A simple and elegant solution is to construct a set from the array which retains only distinct elements. Then simply compare the set's size against the array's length. If both are not the same, then we can say that the array contains duplicates. This works in linear time and space.
ECMAScript 2016 incorporates an includes()
method for arrays that specifically solves the problem, and so is now the preferred method.
[1, 2, 3].includes(2); // true [1, 2, 3].includes(4); // false [1, 2, 3].includes(1, 2); // false (second parameter is the index position in this array at which to begin searching)
As of JULY 2018, this has been implemented in almost all major browsers, if you need to support an older browser a polyfill is available.
Edit: Note that this returns false if the item in the array is an object. This is because similar objects are two different objects in JavaScript.
Code:
function isInArray(value, array) { return array.indexOf(value) > -1; }
Execution:
isInArray(1, [1,2,3]); // true
Update (2017):
In modern browsers which follow the ECMAScript 2016 (ES7) standard, you can use the function Array.prototype.includes, which makes it way more easier to check if an item is present in an array:
const array = [1, 2, 3]; const value = 1; const isInArray = array.includes(value); console.log(isInArray); // true
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