检查数组的所有值是否相等

时间:2022-11-09 13:08:51

I need to find arrays where all values are equal. What's the fastest way to do this? Should I loop through it and just compare values?

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

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

25 个解决方案

#1


102  

Edit: Be a Red ninja:

编辑:做一个红色忍者:

!!array.reduce(function(a, b){ return (a === b) ? a : NaN; });

Results:

结果:

var array = ["a", "a", "a"] => result: "true"
var array = ["a", "b", "a"] => result: "false"
var array = ["false", ""] => result: "false"
var array = ["false", false] => result: "false"
var array = ["false", "false"] => result: "true"
var array = [NaN, NaN] => result: "false" 

Warning:

警告:

var array = [] => result: TypeError thrown

This is because we do not pass an initialValue. So, you may wish to check array.length first.

这是因为我们没有传递初始值。因此,您可能希望检查数组。第一个长度。

#2


70  

const allEqual = arr => arr.every( v => v === arr[0] )
allEqual( [1,1,1,1] )  // true

Or one-liner:

或一行程序:

[1,1,1,1].every( (val, i, arr) => val === arr[0] )   // true

Array.prototype.every (from MDN) : The every() method tests whether all elements in the array pass the test implemented by the provided function.

Array.prototype。every(来自MDN): every()方法测试数组中的所有元素是否通过所提供函数实现的测试。

#3


61  

This works. You create a method on Array by using prototype.

这个作品。您可以使用prototype在数组中创建一个方法。

Array.prototype.allValuesSame = function() {

    for(var i = 1; i < this.length; i++)
    {
        if(this[i] !== this[0])
            return false;
    }

    return true;
}

Call this in this way:

这样称呼它:

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

#4


27  

In JavaScript 1.6, you can use Array.every:

在JavaScript 1.6中,可以使用Array.every:

function AllTheSame(array) {
    var first = array[0];
    return array.every(function(element) {
        return element === first;
    });
}

You probably need some sanity checks, e.g. when the array has no elements. (Also, this won't work when all elements are NaN since NaN !== NaN, but that shouldn't be an issue... right?)

您可能需要一些完整性检查,例如,当数组没有元素时。(当然,当所有的元素都是NaN的时候,这也不会起作用,但这不是问题……)对吗?)

#5


9  

And for performance comparison I also did a benchmark:

为了进行性能比较,我还做了一个基准:

function allAreEqual(array){
    if(!array.length) return true;
    // I also made sure it works with [false, false] array
    return array.reduce(function(a, b){return (a === b)?a:(!b);}) === array[0];
}
function same(a) {
    if (!a.length) return true;
    return !a.filter(function (e) {
        return e !== a[0];
    }).length;
}

function allTheSame(array) {
    var first = array[0];
    return array.every(function(element) {
        return element === first;
    });
}

function useSome(array){
    return !array.some(function(value, index, array){
        return value !== array[0];
    });
}

Results:

结果:

allAreEqual x 47,565 ops/sec ±0.16% (100 runs sampled)
same x 42,529 ops/sec ±1.74% (92 runs sampled)
allTheSame x 66,437 ops/sec ±0.45% (102 runs sampled)
useSome x 70,102 ops/sec ±0.27% (100 runs sampled)

So apparently using builtin array.some() is the fastest method of the ones sampled.

显然,使用builtin array.some()是抽样的方法中最快的一种。

#6


8  

Shortest answer using underscore/lodash

使用下划线/ lodash最短的答案

function elementsEqual(arr) {
    return !_.without(arr, arr[0]).length
}

spec:

规范:

elementsEqual(null) // throws error
elementsEqual([]) // true
elementsEqual({}) // true
elementsEqual([1]) // true
elementsEqual([1,2]) // false
elementsEqual(NaN) // true

edit:

编辑:

Or even shorter, inspired by Tom's answer:

或者更短,受汤姆回答的启发:

function elementsEqual2(arr) {
    return _.uniq(arr).length <= 1;
}

spec:

规范:

elementsEqual2(null) // true (beware, it's different than above)
elementsEqual2([]) // true
elementsEqual2({}) // true
elementsEqual2([1]) // true
elementsEqual2([1,2]) // false
elementsEqual2(NaN) // true

#7


8  

You can turn the Array into a Set. If the size of the Set is equal to 1, then all elements of the Array are equal.

你可以把数组转换成一个集合,如果集合的大小等于1,那么数组的所有元素都是相等的。

function allEqual(arr) {
  return new Set(arr).size == 1;
}

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

#8


6  

If you're already using underscore.js, then here's another option using _.uniq:

如果你已经在使用下划线。然后这里有另一个使用_.uniq的选项:

function allEqual(arr) {
    return _.uniq(arr).length === 1;
}

_.uniq returns a duplicate-free version of the array. If all the values are the same, then the length will be 1.

_。uniq返回数组的无重复版本。如果所有的值都相同,那么长度就是1。

As mentioned in the comments, given that you may expect an empty array to return true, then you should also check for that case:

正如评论中提到的,如果您希望一个空数组返回true,那么您也应该检查一下:

function allEqual(arr) {
    return arr.length === 0 || _.uniq(arr).length === 1;
}

#9


5  

Yes, you can check it also using filter as below, very simple, checking every values are the same as the first one:

是的,你也可以用滤镜检查一下,很简单,检查每个值都和第一个一样:

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

also can be done using every method on the array:

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

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

and you can check your arrays like below:

你可以检查你的数组如下:

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

Or you can add it to native Array functionalities in JavaScript if you reuse it a lot:

或者你可以将它添加到JavaScript的本地数组函数中,如果你经常重复使用它:

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

and you can check your arrays like below:

你可以检查你的数组如下:

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

#10


4  

You can use Array.every if supported:

您可以使用数组。每一个如果支持:

var equals = array.every(function(value, index, array){
    return value === array[0];
});

Alternatives approach of a loop could be something like sort

循环的替代方法可以是排序

var temp = array.slice(0).sort();
var equals = temp[0] === temp[temp.length - 1];

Or, if the items are like the question, something dirty like:

或者,如果项目像问题一样,一些肮脏的东西像:

var equals = array.join('').split(array[0]).join('').length === 0;

Also works.

同样适用。

#11


4  

You can get this one-liner to do what you want using Array.prototype.every, Object.is, and ES6 arrow functions:

您可以使用Array.prototype让这个一行程序做您想做的事情。每一个对象。和ES6箭头函数:

const all = arr => arr.every(x => Object.is(arr[0], x));

#12


3  

I think the simplest way to do this is to create a loop to compare the each value to the next. As long as there is a break in the "chain" then it would return false. If the first is equal to the second, the second equal to the third and so on, then we can conclude that all elements of the array are equal to each other.

我认为最简单的方法是创建一个循环,将每个值与下一个值进行比较。只要“链”有一个断裂,它就会返回false。如果第一项等于第二项,第二项等于第三项等等,那么我们可以得出结论,数组的所有元素都是相等的。

given an array data[], then you can use:

给定一个数组数据[],则可以使用:

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

#13


3  

arr.length && arr.reduce(function(a, b){return (a === b)?a:false;}) === arr[0];

#14


2  

You can use this:

您可以使用:

function same(a) {
    if (!a.length) return true;
    return !a.filter(function (e) {
        return e !== a[0];
    }).length;
}

The function first checks whether the array is empty. If it is it's values are equals.. Otherwise it filter the array and takes all elements which are different from the first one. If there are no such values => the array contains only equal elements otherwise it doesn't.

函数首先检查数组是否为空。如果是,它的值是相等的。否则,它将过滤数组并获取与第一个数组不同的所有元素。如果没有这样的值=>,则数组只包含相等的元素,否则它不会。

#15


2  

Something around this approach should work.

围绕这种方法的一些东西应该是有用的。

a.join(',').split(a[0]).length === a.length + 1

#16


2  

Well, this is really not very complicated. I have strong suspicion you didn't even try. What you do is that you pick the first value, save it in the variable, and then, within a for loop, compare all subsequent values with the first one.
I intentionally didn't share any code. Find how for is used and how variables are compared.

这其实并不复杂。我很怀疑你连试都没试过。您要做的是选择第一个值,将其保存在变量中,然后在for循环中,将所有后续值与第一个值进行比较。我故意不分享任何代码。查找如何使用for和如何比较变量。

#17


2  

Update new solution: check index

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

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

Updated with ES6: Use list.every is the fastest way:

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

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

old version:

旧版本:

      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));
      }

#18


1  

Underscore's _.isEqual(object, other) function seems to work well for arrays. The order of items in the array matter when it checks for equality. See http://underscorejs.org/#isEqual.

下划线_。isEqual(object, other)函数似乎很适合数组。数组中的项的顺序在检查是否相等时很重要。见http://underscorejs.org/ # isEqual。

#19


1  

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

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

#20


1  

Its Simple. Create a function and pass a parameter. In that function copy the first index into a new variable. Then Create a for loop and loop through the array. Inside a loop create an while loop with a condition checking whether the new created variable is equal to all the elements in the loop. if its equal return true after the for loop completes else return false inside the while loop.

它的简单。创建一个函数并传递一个参数。在该函数中,将第一个索引复制到一个新变量中。然后创建一个for循环并循环遍历数组。在循环中创建一个while循环,该循环的条件是检查新创建的变量是否等于循环中的所有元素。如果它在for循环完成后返回true,则在while循环中返回false。

function isUniform(arra){
    var k=arra[0];
    for (var i = 0; i < arra.length; i++) {
        while(k!==arra[i]){
            return false;
        }
    }
    return true;
}

#21


0  

Simple one line solution, just compare it to an array filled with the first entry.

简单的一行解决方案,只需将它与填充第一个条目的数组进行比较。

if(arr.join('') === Array(arr.length).fill(arr[0]).join(''))

#22


0  

Another interesting way when you use ES6 arrow function syntax:

使用ES6箭头函数语法的另一个有趣的方法是:

x = ['a', 'a', 'a', 'a']
!x.filter(e=>e!==x[0])[0]  // true

x = ['a', 'a', 'b', 'a']
!x.filter(e=>e!==x[0])[0] // false

x = []
!x.filter(e=>e!==x[0])[0]  // true

And when you don't want to reuse the variable for array (x):

当你不想为数组(x)重用变量时:

!['a', 'a', 'a', 'a'].filter((e,i,a)=>e!==a[0])[0]    // true

IMO previous poster who used array.every(...) has the cleanest solution.

我以前见过使用array的海报,每个(…)都有最干净的解决方案。

#23


0  

function isUniform(array) {   
  for (var i=1; i< array.length; i++) {
    if (array[i] !== array[0]) { return false; }
  }

  for (var i=1; i< array.length; i++) {
    if (array[i] === array[0]) { return true; }
  }
}
  • For the first loop; whenever it detects uneven, returns "false"
  • 第一循环;当检测到不均匀时,返回“false”
  • The first loop runs, and if it returns false, we have "false"
  • 第一个循环运行,如果返回false,我们有“false”
  • When it's not return false, it means there will be true, so we do the second loop. And of course we will have "true" from the second loop (because the first loop found it's NOT false)
  • 当它没有返回false时,它意味着会有true,所以我们做第二个循环。当然,我们会从第二个循环中得到“true”(因为第一个循环发现它不是false)

#24


0  

this might work , you can use the comment out code as well that also woks well with the given scenerio.

这可能有用,您也可以使用注释输出代码,它也可以与给定的scenerio很好地配合。

function isUniform(){
	var arrayToMatch = [1,1,1,1,1];
	var temp = arrayToMatch[0];
	console.log(temp);
  /* return arrayToMatch.every(function(check){
    return check == temp;
   });*/
var bool;
   arrayToMatch.forEach(function(check){
    bool=(check == temp);
   })
  console.log(bool);
}
isUniform();

#25


-2  

In PHP, there is a solution very simple, one line method :

在PHP中,有一个非常简单的解决方案,即一行法:

(count(array_count_values($array)) == 1)

(计数(中的键(数组)美元)= = 1)

For example :

例如:

$arr1 = ['a', 'a', 'a', 'a'];
$arr2 = ['a', 'a', 'b', 'a'];


print (count(array_count_values($arr1)) == 1 ? "identical" : "not identical"); // identical
print (count(array_count_values($arr2)) == 1 ? "identical" : "not identical"); // not identical

That's all.

这是所有。

#1


102  

Edit: Be a Red ninja:

编辑:做一个红色忍者:

!!array.reduce(function(a, b){ return (a === b) ? a : NaN; });

Results:

结果:

var array = ["a", "a", "a"] => result: "true"
var array = ["a", "b", "a"] => result: "false"
var array = ["false", ""] => result: "false"
var array = ["false", false] => result: "false"
var array = ["false", "false"] => result: "true"
var array = [NaN, NaN] => result: "false" 

Warning:

警告:

var array = [] => result: TypeError thrown

This is because we do not pass an initialValue. So, you may wish to check array.length first.

这是因为我们没有传递初始值。因此,您可能希望检查数组。第一个长度。

#2


70  

const allEqual = arr => arr.every( v => v === arr[0] )
allEqual( [1,1,1,1] )  // true

Or one-liner:

或一行程序:

[1,1,1,1].every( (val, i, arr) => val === arr[0] )   // true

Array.prototype.every (from MDN) : The every() method tests whether all elements in the array pass the test implemented by the provided function.

Array.prototype。every(来自MDN): every()方法测试数组中的所有元素是否通过所提供函数实现的测试。

#3


61  

This works. You create a method on Array by using prototype.

这个作品。您可以使用prototype在数组中创建一个方法。

Array.prototype.allValuesSame = function() {

    for(var i = 1; i < this.length; i++)
    {
        if(this[i] !== this[0])
            return false;
    }

    return true;
}

Call this in this way:

这样称呼它:

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

#4


27  

In JavaScript 1.6, you can use Array.every:

在JavaScript 1.6中,可以使用Array.every:

function AllTheSame(array) {
    var first = array[0];
    return array.every(function(element) {
        return element === first;
    });
}

You probably need some sanity checks, e.g. when the array has no elements. (Also, this won't work when all elements are NaN since NaN !== NaN, but that shouldn't be an issue... right?)

您可能需要一些完整性检查,例如,当数组没有元素时。(当然,当所有的元素都是NaN的时候,这也不会起作用,但这不是问题……)对吗?)

#5


9  

And for performance comparison I also did a benchmark:

为了进行性能比较,我还做了一个基准:

function allAreEqual(array){
    if(!array.length) return true;
    // I also made sure it works with [false, false] array
    return array.reduce(function(a, b){return (a === b)?a:(!b);}) === array[0];
}
function same(a) {
    if (!a.length) return true;
    return !a.filter(function (e) {
        return e !== a[0];
    }).length;
}

function allTheSame(array) {
    var first = array[0];
    return array.every(function(element) {
        return element === first;
    });
}

function useSome(array){
    return !array.some(function(value, index, array){
        return value !== array[0];
    });
}

Results:

结果:

allAreEqual x 47,565 ops/sec ±0.16% (100 runs sampled)
same x 42,529 ops/sec ±1.74% (92 runs sampled)
allTheSame x 66,437 ops/sec ±0.45% (102 runs sampled)
useSome x 70,102 ops/sec ±0.27% (100 runs sampled)

So apparently using builtin array.some() is the fastest method of the ones sampled.

显然,使用builtin array.some()是抽样的方法中最快的一种。

#6


8  

Shortest answer using underscore/lodash

使用下划线/ lodash最短的答案

function elementsEqual(arr) {
    return !_.without(arr, arr[0]).length
}

spec:

规范:

elementsEqual(null) // throws error
elementsEqual([]) // true
elementsEqual({}) // true
elementsEqual([1]) // true
elementsEqual([1,2]) // false
elementsEqual(NaN) // true

edit:

编辑:

Or even shorter, inspired by Tom's answer:

或者更短,受汤姆回答的启发:

function elementsEqual2(arr) {
    return _.uniq(arr).length <= 1;
}

spec:

规范:

elementsEqual2(null) // true (beware, it's different than above)
elementsEqual2([]) // true
elementsEqual2({}) // true
elementsEqual2([1]) // true
elementsEqual2([1,2]) // false
elementsEqual2(NaN) // true

#7


8  

You can turn the Array into a Set. If the size of the Set is equal to 1, then all elements of the Array are equal.

你可以把数组转换成一个集合,如果集合的大小等于1,那么数组的所有元素都是相等的。

function allEqual(arr) {
  return new Set(arr).size == 1;
}

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

#8


6  

If you're already using underscore.js, then here's another option using _.uniq:

如果你已经在使用下划线。然后这里有另一个使用_.uniq的选项:

function allEqual(arr) {
    return _.uniq(arr).length === 1;
}

_.uniq returns a duplicate-free version of the array. If all the values are the same, then the length will be 1.

_。uniq返回数组的无重复版本。如果所有的值都相同,那么长度就是1。

As mentioned in the comments, given that you may expect an empty array to return true, then you should also check for that case:

正如评论中提到的,如果您希望一个空数组返回true,那么您也应该检查一下:

function allEqual(arr) {
    return arr.length === 0 || _.uniq(arr).length === 1;
}

#9


5  

Yes, you can check it also using filter as below, very simple, checking every values are the same as the first one:

是的,你也可以用滤镜检查一下,很简单,检查每个值都和第一个一样:

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

also can be done using every method on the array:

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

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

and you can check your arrays like below:

你可以检查你的数组如下:

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

Or you can add it to native Array functionalities in JavaScript if you reuse it a lot:

或者你可以将它添加到JavaScript的本地数组函数中,如果你经常重复使用它:

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

and you can check your arrays like below:

你可以检查你的数组如下:

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

#10


4  

You can use Array.every if supported:

您可以使用数组。每一个如果支持:

var equals = array.every(function(value, index, array){
    return value === array[0];
});

Alternatives approach of a loop could be something like sort

循环的替代方法可以是排序

var temp = array.slice(0).sort();
var equals = temp[0] === temp[temp.length - 1];

Or, if the items are like the question, something dirty like:

或者,如果项目像问题一样,一些肮脏的东西像:

var equals = array.join('').split(array[0]).join('').length === 0;

Also works.

同样适用。

#11


4  

You can get this one-liner to do what you want using Array.prototype.every, Object.is, and ES6 arrow functions:

您可以使用Array.prototype让这个一行程序做您想做的事情。每一个对象。和ES6箭头函数:

const all = arr => arr.every(x => Object.is(arr[0], x));

#12


3  

I think the simplest way to do this is to create a loop to compare the each value to the next. As long as there is a break in the "chain" then it would return false. If the first is equal to the second, the second equal to the third and so on, then we can conclude that all elements of the array are equal to each other.

我认为最简单的方法是创建一个循环,将每个值与下一个值进行比较。只要“链”有一个断裂,它就会返回false。如果第一项等于第二项,第二项等于第三项等等,那么我们可以得出结论,数组的所有元素都是相等的。

given an array data[], then you can use:

给定一个数组数据[],则可以使用:

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

#13


3  

arr.length && arr.reduce(function(a, b){return (a === b)?a:false;}) === arr[0];

#14


2  

You can use this:

您可以使用:

function same(a) {
    if (!a.length) return true;
    return !a.filter(function (e) {
        return e !== a[0];
    }).length;
}

The function first checks whether the array is empty. If it is it's values are equals.. Otherwise it filter the array and takes all elements which are different from the first one. If there are no such values => the array contains only equal elements otherwise it doesn't.

函数首先检查数组是否为空。如果是,它的值是相等的。否则,它将过滤数组并获取与第一个数组不同的所有元素。如果没有这样的值=>,则数组只包含相等的元素,否则它不会。

#15


2  

Something around this approach should work.

围绕这种方法的一些东西应该是有用的。

a.join(',').split(a[0]).length === a.length + 1

#16


2  

Well, this is really not very complicated. I have strong suspicion you didn't even try. What you do is that you pick the first value, save it in the variable, and then, within a for loop, compare all subsequent values with the first one.
I intentionally didn't share any code. Find how for is used and how variables are compared.

这其实并不复杂。我很怀疑你连试都没试过。您要做的是选择第一个值,将其保存在变量中,然后在for循环中,将所有后续值与第一个值进行比较。我故意不分享任何代码。查找如何使用for和如何比较变量。

#17


2  

Update new solution: check index

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

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

Updated with ES6: Use list.every is the fastest way:

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

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

old version:

旧版本:

      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));
      }

#18


1  

Underscore's _.isEqual(object, other) function seems to work well for arrays. The order of items in the array matter when it checks for equality. See http://underscorejs.org/#isEqual.

下划线_。isEqual(object, other)函数似乎很适合数组。数组中的项的顺序在检查是否相等时很重要。见http://underscorejs.org/ # isEqual。

#19


1  

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

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

#20


1  

Its Simple. Create a function and pass a parameter. In that function copy the first index into a new variable. Then Create a for loop and loop through the array. Inside a loop create an while loop with a condition checking whether the new created variable is equal to all the elements in the loop. if its equal return true after the for loop completes else return false inside the while loop.

它的简单。创建一个函数并传递一个参数。在该函数中,将第一个索引复制到一个新变量中。然后创建一个for循环并循环遍历数组。在循环中创建一个while循环,该循环的条件是检查新创建的变量是否等于循环中的所有元素。如果它在for循环完成后返回true,则在while循环中返回false。

function isUniform(arra){
    var k=arra[0];
    for (var i = 0; i < arra.length; i++) {
        while(k!==arra[i]){
            return false;
        }
    }
    return true;
}

#21


0  

Simple one line solution, just compare it to an array filled with the first entry.

简单的一行解决方案,只需将它与填充第一个条目的数组进行比较。

if(arr.join('') === Array(arr.length).fill(arr[0]).join(''))

#22


0  

Another interesting way when you use ES6 arrow function syntax:

使用ES6箭头函数语法的另一个有趣的方法是:

x = ['a', 'a', 'a', 'a']
!x.filter(e=>e!==x[0])[0]  // true

x = ['a', 'a', 'b', 'a']
!x.filter(e=>e!==x[0])[0] // false

x = []
!x.filter(e=>e!==x[0])[0]  // true

And when you don't want to reuse the variable for array (x):

当你不想为数组(x)重用变量时:

!['a', 'a', 'a', 'a'].filter((e,i,a)=>e!==a[0])[0]    // true

IMO previous poster who used array.every(...) has the cleanest solution.

我以前见过使用array的海报,每个(…)都有最干净的解决方案。

#23


0  

function isUniform(array) {   
  for (var i=1; i< array.length; i++) {
    if (array[i] !== array[0]) { return false; }
  }

  for (var i=1; i< array.length; i++) {
    if (array[i] === array[0]) { return true; }
  }
}
  • For the first loop; whenever it detects uneven, returns "false"
  • 第一循环;当检测到不均匀时,返回“false”
  • The first loop runs, and if it returns false, we have "false"
  • 第一个循环运行,如果返回false,我们有“false”
  • When it's not return false, it means there will be true, so we do the second loop. And of course we will have "true" from the second loop (because the first loop found it's NOT false)
  • 当它没有返回false时,它意味着会有true,所以我们做第二个循环。当然,我们会从第二个循环中得到“true”(因为第一个循环发现它不是false)

#24


0  

this might work , you can use the comment out code as well that also woks well with the given scenerio.

这可能有用,您也可以使用注释输出代码,它也可以与给定的scenerio很好地配合。

function isUniform(){
	var arrayToMatch = [1,1,1,1,1];
	var temp = arrayToMatch[0];
	console.log(temp);
  /* return arrayToMatch.every(function(check){
    return check == temp;
   });*/
var bool;
   arrayToMatch.forEach(function(check){
    bool=(check == temp);
   })
  console.log(bool);
}
isUniform();

#25


-2  

In PHP, there is a solution very simple, one line method :

在PHP中,有一个非常简单的解决方案,即一行法:

(count(array_count_values($array)) == 1)

(计数(中的键(数组)美元)= = 1)

For example :

例如:

$arr1 = ['a', 'a', 'a', 'a'];
$arr2 = ['a', 'a', 'b', 'a'];


print (count(array_count_values($arr1)) == 1 ? "identical" : "not identical"); // identical
print (count(array_count_values($arr2)) == 1 ? "identical" : "not identical"); // not identical

That's all.

这是所有。