Javascript 检查数组的所有值是否相等
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14832603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if all values of array are equal
提问by Marvin3
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
回答by golopot
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()方法测试数组中的所有元素是否通过提供的函数实现的测试。
回答by Martin
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.lengthfirst.
这是因为我们没有传递一个initialValue。所以,你不妨先检查一下array.length。
回答by Robert Fricke
This works. You create a method on Array by using 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;
}
}
Call this in this way:
以这种方式调用它:
let a = ['a', 'a', 'a'];
let b = a.allValuesSame(); // true
a = ['a', 'b', 'a'];
b = a.allValuesSame(); // false
回答by Mattias Buelens
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 NaNsince NaN !== NaN, but that shouldn't be an issue... right?)
您可能需要进行一些完整性检查,例如当数组没有元素时。(此外,当所有元素都为NaNafter时,这将不起作用NaN !== NaN,但这应该不是问题......对吗?)
回答by Huy Tran
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.
您可以将 Array 转换为 Set。如果 Set 的大小等于 1,则 Array 的所有元素都相等。
function allEqual(arr) {
return new Set(arr).size == 1;
}
allEqual(['a', 'a', 'a', 'a']); // true
allEqual(['a', 'a', 'b', 'a']); // false
回答by Martin
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.
因此,显然使用内置 array.some() 是采样方法中最快的方法。
回答by average Joe
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
回答by Tom Fenech
If you're already using underscore.js, then here's another option using _.uniq:
如果您已经在使用underscore.js,那么这里有另一个使用选项_.uniq:
function allEqual(arr) {
return _.uniq(arr).length === 1;
}
_.uniqreturns 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;
}
回答by Alireza
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 中的原生 Array 功能中:
//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
回答by Noor
You can get this one-liner to do what you want using Array.prototype.every, Object.is, and ES6 arrow functions:
你可以使用Array.prototype.every、Object.is和 ES6 箭头函数让这个单行代码做你想做的事:
const all = arr => arr.every(x => Object.is(arr[0], x));

