Articles

Affichage des articles du avril, 2018

How to check if an array includes an objet in Jquery ?

How do i check if an array includes an object in Jquery ? Use something like this: function containsObject ( obj , list ) { var i ; for ( i = 0 ; i < list . length ; i ++) { if ( list [ i ] === obj ) { return true ; } } return false ; } In this case,  containsObject(car4, carBrands)  is true. Remove the  carBrands.push(car4);  call and it will return false instead. If you later expand to using objects to store these other car objects instead of using arrays, you could use something like this instead: function containsObject ( obj , list ) { var x ; for ( x in list ) { if ( list . hasOwnProperty ( x ) && list [ x ] === obj ) { return true ; } } return false ; } This approach will work for arrays too, but when used on arrays it will be a tad slower than the first option.

How do I check if an array includes an object in JavaScript?

Similar thing: Finds the first element by a "search lambda": Array . prototype . find = function ( search_lambda ) { return this [ this . map ( search_lambda ). indexOf ( true )]; }; Usage: [ 1 , 3 , 4 , 5 , 8 , 3 , 5 ]. find ( function ( item ) { return item % 2 == 0 }) => 4 Same in coffeescript: Array . prototype . find = ( search_lambda ) -> @[ @map ( search_lambda ). indexOf ( true )] Current browsers have  Array#includes , which does  exactly  that,  is widely supported , and has a  polyfill  for older browsers. You can also use  Array#indexOf , which is less direct, but doesn't require Polyfills for out of date browsers. jQuery offers  $.inArray , which is functionally equivalent to  Array#indexOf . underscore.js , a JavaScript utility library, offers  _.contains(list, value) , alias  _.include(list, value) , both of which use  indexOf  internally if passed a JavaScript arra...