我需要找到所有值都相等的数组。最快的方法是什么?我应该循环遍历它,然后比较值吗?

['a', 'a', 'a', 'a'] // true
['a', 'a', 'b', 'a'] // false

当前回答

你可以计算数组中不同值的数量,如果这个值是1,所有的条目都是相同的。

例子:

array = np.array([1, 2, 2, 3, 3])
set(array) # this gives the different values present in the array (1,2,3)
len(set(array)) # this returns 3, 3 different values in the array

其他回答

**// Logical Solution:- Declare global array and one variable(To check the condition) whether all element of an array contains same value or not.**

    var arr =[];
    var isMatching = false;

    for(var i=0;i<arr.length;i++){
            if(String(arr[i]).toLowerCase()== "Your string to check"){
                isMatching=true;
                // Array has same value in all index of an array
            }
            else{
                isMatching=false;
                // Array Doesn't has same value in all index of an array
                break;
            }
        }
    // **Check isMatching variable is true or false**

        if(isMatching){ // True
            //If Array has same value in all index, then this block will get executed
        }
        else{ //False
            //If Array doesn't has same value in all index, then this block will get executed
        }

这个作品。通过使用prototype在Array上创建一个方法。

if (Array.prototype.allValuesSame === undefined) {
  Array.prototype.allValuesSame = function() {
    for (let i = 1; i < this.length; i++) {
      if (this[i] !== this[0]) {
        return false;
      }
    }
    return true;
  }
}

这样调用它:

let a = ['a', 'a', 'a'];
let b = a.allValuesSame(); // true
a = ['a', 'b', 'a'];
b = a.allValuesSame();     // false

我认为最简单的方法是创建一个循环来比较每个值和下一个值。只要“链”中有断点,它就会返回false。如果第一个元素等于第二个元素,第二个元素等于第三个元素,以此类推,那么我们可以得出这样的结论:数组中的所有元素彼此相等。

给定一个数组data[],那么你可以使用:

for(x=0;x<data.length - 1;x++){
    if (data[x] != data[x+1]){
        isEqual = false;            
    }
}
alert("All elements are equal is " + isEqual);

是的,你也可以使用过滤器检查它,如下所示,非常简单,检查每个值都与第一个相同:

//ES6
function sameValues(arr) {
  return arr.filter((v,i,a)=>v===a[0]).length === arr.length;
} 

也可以使用数组上的每个方法:

//ES6
function sameValues(arr) {
  return arr.every((v,i,a)=>v===a[0]);
} 

你可以像下面这样检查你的数组:

sameValues(['a', 'a', 'a', 'a']); // true
sameValues(['a', 'a', 'b', 'a']); // false

或者,如果你经常重用它,你可以将它添加到JavaScript的原生数组功能中:

//ES6
Array.prototype.sameValues = Array.prototype.sameValues || function(){
 this.every((v,i,a)=>v===a[0]);
}

你可以像下面这样检查你的数组:

['a', 'a', 'a', 'a'].sameValues(); // true
['a', 'a', 'b', 'a'].sameValues(); // false

更新2022版本:使用Set()

     let a = ['a', 'a', 'b', 'a'];
     let b = ['a', 'a', 'a', 'a'];
     const check = (list) => {
        const setItem = new Set(list);
        return setItem.size <= 1;
     }

     const checkShort = (list) => (new Set(list)).size <= 1        
     
      check(a); // false;
      check(b); // true;
      checkShort(a); // false
      checkShort(b); // true

更新新的解决方案:检查索引

 let a = ['a', 'a', 'b', 'a'];
 let b = ['a', 'a', 'a', 'a'];
 let check = (list) => list.every(item => list.indexOf(item) === 0);
 check(a); // false;
 check(b); // true;
   

在ES6更新: 使用列表。每一种方法都是最快的:

 let a = ['a', 'a', 'b', 'a'];
 let check = (list) => list.every(item => item === list[0]);
   

旧版本:

      var listTrue = ['a', 'a', 'a', 'a'];
      var listFalse = ['a', 'a', 'a', 'ab'];

      function areWeTheSame(list) { 
         var sample = list[0];
         return (list.every((item) => item === sample));
      }