5

An array can contains multiple values. I want to check whether all the values are 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

eisbehr
  • 12,243
  • 7
  • 38
  • 63
Shan Biswas
  • 397
  • 2
  • 8
  • 24
  • 3
    Possible duplicate of [How to know if two arrays have the same values](http://stackoverflow.com/questions/6229197/how-to-know-if-two-arrays-have-the-same-values), [How to check if two arrays are equal with JavaScript?](http://stackoverflow.com/questions/3115982/how-to-check-if-two-arrays-are-equal-with-javascript) – Alex K. Aug 03 '16 at 12:55
  • you can use underscore.js for the simplicity and use _.difference([2, 4, 7, 2, 8], [2, 2, 2, 2, 2]); – Sunil Aug 03 '16 at 12:58

5 Answers5

6

You can try like this:

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 the MDN for Array.prototype.every()

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • 1
    I'd suggest a slight refinement: `return arr.slice(1).every(v => arr[0]);` on the grounds there's no need to check if `arr[0] === arr[0]`; but it's a micro-optimisation at best; and might not be an optimisation at all, if it takes longer to slice the array than it does to needlessly compare the first array element to itself. – David Thomas Aug 03 '16 at 12:58
  • 1
    Wow, great code, works fine. Thank you @Rahul – Shan Biswas Aug 04 '16 at 05:01
0

Check 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
KAD
  • 10,972
  • 4
  • 31
  • 73
0

It's possible using an array reduce:

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
Lew
  • 1,248
  • 8
  • 13
0

You can do this in one line using not function from Jquery

var test= $(a).not(b).length === 0;

JsFiddle example

GH Karim
  • 323
  • 1
  • 6
0

If you have access to 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));
MinusFour
  • 13,913
  • 3
  • 30
  • 39