An array may contain multiple values. I want to check if the values are the same or different.
Example
var a = [2, 4, 7, 2, 8]; // all values are not same var b = [2, 2, 2, 2, 2]; // all values are same
How can I check it in jquery
You can try the following:
var a = [2, 4, 7, 2, 8]; var b = [2, 2, 2, 2, 2]; function myFunc(arr){ var x= arr[0]; return arr.every(function(item){ return item=== x; }); } alert(myFunc(a)); alert(myFunc(b));
See MDN for Array.prototype.every ()
Check out this solution.
function arrayUnique(array) { function onlyUnique(value, index, self) { return self.indexOf(value) === index; } var unique = array.filter( onlyUnique ); return (unique.length == 1); } // usage example: var a = [2, 3, 2, 2, 2]; console.log('Array is unique : ' + arrayUnique(a)); // Array is unique : false var b = [2, 2, 2, 2, 2]; console.log('Array is unique : ' + arrayUnique(b)); // Array is unique : true
:
Array.prototype.areAllTheSame = function() { if(!this.length) return false return this.reduce(function(p, c) { return [c, c==p[0] && p[1]] }, [this[0], true])[1] } var arr = [1,2,3,4] var arr2 = [2,2,2,2] arr.areAllTheSame() //-->false arr2.areAllTheSame() //-->true
, JQuery
var test= $(a).not(b).length === 0;
JsFiddle
Set:
Set
var a = [2, 4, 7, 2, 8]; var b = [2, 2, 2, 2, 2]; function onlyOneValue(arr){ return [...new Set(arr)].length < 2; } document.write(onlyOneValue(a) + '<br>'); document.write(onlyOneValue(b));
Source: https://habr.com/ru/post/1650036/More articles:Как изменить цвет только одного столбца в Barchart, используя Chart.js - javascriptHow to use getUserMedia with Cordova on Android? - javascriptType f in pointfree style? - haskellNo matching found for swagger-resources / configuration / ui - javaIn typescript, how to determine the type of an asynchronous function - typescriptResolving ES6 Redundant Import Path in Webpack 2 - webpackreceiving file updates from an ftp server using an inbound channel adapter - javaFind use of lombok created constructor in Intellij - intellij-ideahttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1650040/limit-connections-to-database-with-entity-framework-c&usg=ALkJrhiR_ULVTAptUNrZur5ir3advA0sDQNo heap profiling data for Data.ByteString module - haskellAll Articles