A
Small inductionThe task of searching for the element in the mass is often enough for everyone to write how it can be done.They're usually searching for type elements in the body. Number♪ String or Object♪ Of course, the fastest way to find is by type elements. Numbera comparison of the number, even very large, is going very fast, much easier to check one element than to read the lines, and the objects are even different. If we're looking for the exact object we've added to the mass, that is, that's how fast we compare the numbers, but if we have to look at the properties of the object, it can be very and very prolonged. In particularly difficult cases, I advise you to set up some kind of hesh object and build a separate set of maps where you can find everything you need to find.We'll figure out six ways to do it on the Native JS with different new ways and three ways to deal with them on popular frimetres: http://jquery.com/ ♪ http://underscorejs.ru and https://lodash.com/ ♪Part one, naive, alegro styleFirst of all, you have to go through your own language and see what you can do.Foresee.Let's just try to follow the elements of the mass until we meet what we need. As always, the simplest solution is on average the fastest.function contains(arr, elem) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === elem) {
return true;
}
}
return false;
}
Works everywhere. Compars strictly with help ===♪ Easier to be replaced by ==it can be useful when the elements of a range of different types, but can slow down the search. It can and can be modified by adding an opportunity to start searching the element at the end. Looking for numbers, lines. By expanding a little, you might add the possibility of finding a piece of your condition (this will help us look at the properties of the object or, for example, the first element, which is more than 100500):function contains(arr, pred) {
for (var i = 0; i < arr.length; i++) {
if (typeof pred == 'function' && pred(arr[i], i, arr) || arr[i] === elem) {
return true;
}
}
return false;
}
Array.prototype.indexOf() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf - an old-fashioned method that makes everyone suffer with their own -1 In case there is no element.function contains(arr, elem) {
return arr.indexOf(elem) != -1;
}
He's kept everywhere except IE Circum=7, but it's a long forgotten joke. This method is used to search the element strictly from the lower index to the larger, using the comparison ===♪ Alas, according to the properties of the facility, we can't look for that. arr.indexOf(searchElement, fromIndex) Adopts two arguments, one searchElement - that's the element that we're looking for, and the second, fromIndexthe index from which to start looking (the interpreter speaks to start searching with the arr.length + fromIndex index. Be careful if you point out fromIndex More lengths of the mass, the method of unthinkable return -1♪function contains(arr, elem, from) {
return arr.indexOf(elem, from) != -1;
}
Array.prototype.lastIndexOf() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf - justice for you, too. Works exactly the same way. Array.prototype.indexOf()but only completely reversed. fromIndex is initially counted at the end. Changed design. ret != -1 ♪ !!~ret for fun.function contains(arr, elem, from) {
return !!~arr.lastIndexOf(elem, from);
}
Array.prototype.find() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find - Modified style and youth ES6, with all the following:function contains(arr, elem) {
return arr.find((i) => i === elem) != -1;
}
Return the element or -1if nothing is found. Looking for help. callback(elem, index, arr)I mean, if this function comes back truethat's the right element. Of course, this function can be applied to itself, so the method is universal.Array.prototype.findIndex() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex - A completely similar to the previous method, except that the function does not return the element but the index. I'll give her the opportunity to transfer my function:function contains(arr, pred) {
var f = typeof pred == 'function' ? pred : ( i => i === pred );
return arr.findIndex(f) != -1;
}
Array.prototype.includes() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes - and it's ES7, and it's still very raw. Finally, we'll have a special method to find out if there's an element in the mass! Congratulations!arr.includes(elem);
That's all you need to find the element. Arguments in this function are entirely similar Array.prototype.indexOf()♪ He'll come back. true if successful and false We're going back. Of course you can't look at the properties of the objects. Array.prototype.find()♪ Must be the fastest, but... Maybe he'll be the fastest in time.Part two, with attention, but alien and saint styleNow, finally, we can talk about the same subject, but in the context of a couple of frimvors! They say it's always good to see what others do before you start doing it yourself. Maybe it'll give us some interesting eyes!jQuery http://api.jquery.com/jQuery.inArray/ - By the way, it's a very fast method, in tests. Uses strict equality inside === and returns -1If you haven't found anything, and if you've found it, the index will return. For comfort and the sameness, we'll take it as a function:function contains(arr, elem) {
return jQuery.inArray( elem, arr) != -1;
}
Now let's talk about how she works. That's what she represents in the story. 2.1.3:inArray: function( elem, arr, i ) {
return arr == null ? -1 : indexOf.call( arr, elem, i );
}
Where? indexOf This is this:// Use a stripped-down indexOf as it's faster than native
// http://jsperf.com/thor-indexof-vs-for/5
indexOf = function( list, elem ) {
var i = 0,
len = list.length;
for ( ; i < len; i++ ) {
if ( list[i] === elem ) {
return i;
}
}
return -1;
}
Funny comment says it's faster than your own. Array.prototype.indexOf() (may suggest that due to the lack of all checks) and suggest that the performance tests be examined.In fact, this is the first way from the first part.Underscore http://underscorejs.ru/#contains - That's how we offer a popular library to work with the collections. The same as that. _.include(list, value)♪Used === for comparison. Come back. trueif list There's an element we're looking for. If the list is a mass, the indexOf method will be generated._.contains = _.include = function(obj, target) {
if (obj == null) return false;
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
return any(obj, function(value) {
return value === target;
});
};
Where? nativeIndexOf - the thing that says Array.prototype.indexOf() exists, a obj.indexOf === nativeIndexOf Says list - A mass. Now it is understandable why this method is slower than jQuery.inArray()Just a wrapper. Array.prototype.indexOf()♪ Nothing interesting.Lodash https://lodash.com/docs#includes - That's the last hope for new thoughts from the second famous library to work with the collections. Same thing _.contains() and _.include()♪Come back. trueif it contains and false If not. fromIndex An index of the element from which the search begins.function includes(collection, target, fromIndex, guard) {
var length = collection ? getLength(collection) : 0;
if (!isLength(length)) {
collection = values(collection);
length = collection.length;
}
if (typeof fromIndex != 'number' || (guard && isIterateeCall(target, fromIndex, guard))) {
fromIndex = 0;
} else {
fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0);
}
return (typeof collection == 'string' || !isArray(collection) && isString(collection))
? (fromIndex <= length && collection.indexOf(target, fromIndex) > -1)
: (!!length && getIndexOf(collection, target, fromIndex) > -1);
}
guard - an argument. First, the length of the collection, selected fromIndexAnd then... no, no. Array.prototype.indexOf()! For locator search, used String.prototype.indexOf()And we're going further _.getIndexOf() And as a result, we'll get into the L.A. indexOf():function indexOf(array, value, fromIndex) {
var length = array ? array.length : 0;
if (!length) {
return -1;
}
if (typeof fromIndex == 'number') {
fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex;
} else if (fromIndex) {
var index = binaryIndex(array, value);
if (index < length &&
(value === value ? (value === array[index]) : (array[index] !== array[index]))) {
return index;
}
return -1;
}
return baseIndexOf(array, value, fromIndex || 0);
}
She's interesting that fromIndex may be taken as Numberand Boolean And if it's all the same as the buoy type and it's not. true, the function will use the binary search on the mass! Nice. Otherwise, it's done. indexOf() bye-bye:function baseIndexOf(array, value, fromIndex) {
if (value !== value) {
return indexOfNaN(array, fromIndex);
}
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
That's an interesting move for a case we're looking for. NaN (I remember that because of an unfortunate mistake, he is not equal to himself). Implemented indexOfNaN()and indeed none of the ways described earlier could find NaNexcept where, naturally, we could specify the function for the selection of elements.Can I just offer you away? _.indexOf() to search the element:function contains(arr, elem, fromIndex) {
return _.indexOf(arr, elem, fromIndex) != -1;
}
Where? fromIndex it's either an index where we start looking or trueif we know that arr distorted.Conclusion, albeit in the form of an intermezcoAnd, yes, all these options make sense only if the time of data search is frequent in your algorithm or searching is very large. Here, I'll bring down some type of tests below. Number and String in lengths of 1,000000 (million) elements for three cases where the element is at the beginning of the mass, in the middle (may be considered to be thepoint of the average deck) and at the end (may be counted at the time of search of the missing element other than the method of the missing element) Array.prototype.lastIndexOf()) http://jsperf.com/testfindeleminarray/8 ; http://jsperf.com/testfindeleminarray/9 ; http://jsperf.com/testfindeleminarray/10 ; http://jsperf.com/testfindeleminarray/13 ; http://jsperf.com/testfindeleminarray/12 ; http://jsperf.com/testfindeleminarray/11 ♪The results of the tests can depend very much on the browser version, and also on the browsers themselves, how I don't know, but I recommend protesting several. On average, it's seen that the first way out of the first part (written by hand) wins everywhere, and the second place usually divides the lodash and Array.prototype.includes()♪Yes, I'm asking you that if you're going to get in your head to look. NaNthat might not be possible in almost all the methods, NaN !== NaN♪