我需要找到所有值都相等的数组。最快的方法是什么?我应该循环遍历它,然后比较值吗?
['a', 'a', 'a', 'a'] // true
['a', 'a', 'b', 'a'] // false
我需要找到所有值都相等的数组。最快的方法是什么?我应该循环遍历它,然后比较值吗?
['a', 'a', 'a', 'a'] // true
['a', 'a', 'b', 'a'] // false
当前回答
这可能会起作用,你也可以使用注释代码,这也适用于给定的场景。
函数isUniform () { var arrayToMatch = [1,1,1,1,1]; var temp = arrayToMatch[0]; console.log(临时); /*返回arrayToMatch.every(函数(检查){ 返回检查== temp; }); * / var bool; arrayToMatch.forEach(函数(检查){ Bool =(check == temp); }) console.log (bool); } isUniform ();
其他回答
你可以用这个:
function same(a) {
if (!a.length) return true;
return !a.filter(function (e) {
return e !== a[0];
}).length;
}
该函数首先检查数组是否为空。如果是的话,它的值是相等的。 否则,它会过滤数组并获取与第一个不同的所有元素。如果没有=>这样的值,则数组只包含相等的元素,否则不包含。
简单的一行解决方案,只需将其与充满第一个条目的数组进行比较。
if(arr.join('') === Array(arr.length).fill(arr[0]).join(''))
更新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));
}
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);
}));
}
你可以计算数组中不同值的数量,如果这个值是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