我需要找到所有值都相同的矩阵。我应该如何遍历数组以比较这些值?
示例正确:
[{"id": 1 ,"value": cow},{"id": 1 ,"value": cow},{"id": 1 ,"value": cow}] // true
错误示例:
[{"id": 1 ,"value": cow},{"id": 2 ,"value": cat},{"id": 1 ,"value": cow}] // false
谢谢
答案 0 :(得分:2)
您可以将数组中的每个元素与第一个元素进行比较,如果所有元素都相等,则意味着数组中的每个元素都相同:
const input = [{"id": 1 ,"value": 'cow'},{"id": 1 ,"value": 'cow'},{"id": 1 ,"value": 'cow'}];
const [ first, ...rest ] = input;
const result = rest.every((entry) => entry.id === first.id && entry.value === first.value);
console.log(result);
答案 1 :(得分:1)
您也可以那样做
var ex1=[{"id": 1 ,"value": "cow"},{"id": 1 ,"value": "cow"},{"id": 1 ,"value": "cow"}] // true
var ex2=[{"id": 1 ,"value": "cow"},{"id": 2 ,"value": "cat"},{"id": 1 ,"value": "cow"}] // false
console.log([...new Set(ex1.map(item => item.id && item.value))].length==1);
console.log([...new Set(ex2.map(item => item.id && item.value))].length==1);
答案 2 :(得分:1)
如果数组中的对象看起来像您的对象,那么您就得到了答案。但是,如果您有很多属性,而不仅仅是id
和value
,则可以尝试以下方法:
// This equals function is written with the help of `https://stackoverflow.com/a/6713782/4610740` Special thanks to him.
Object.prototype.equals = function( that ) {
if ( this === that ) return true;
if ( ! ( this instanceof Object ) || ! ( that instanceof Object ) ) return false;
if ( this.constructor !== that.constructor ) return false;
for ( var p in this ) {
if ( ! this.hasOwnProperty( p ) ) continue;
if ( ! that.hasOwnProperty( p ) ) return false;
if ( this[ p ] === that[ p ] ) continue;
if ( typeof( this[ p ] ) !== "object" ) return false;
if ( ! Object.equals( this[ p ], that[ p ] ) ) return false;
}
for ( p in that ) {
if ( that.hasOwnProperty( p ) && ! this.hasOwnProperty( p ) ) return false;
}
return true;
}
function isSame(array) {
const [first, ...others] = array;
return isEqual = others.every(item => item.equals(first));
}
const data = [{"id": 1 ,"value": "cow"},{"id": 1 ,"value": "cow"},{"id": 1 ,"value": "cow"}];
const data2 = [{"id": 1 ,"value": "cow"},{"id": 2 ,"value": "cat"},{"id": 1 ,"value": "cow"}];
console.log(isSame(data));
console.log(isSame(data2));
.as-console-wrapper{min-height: 100%!important; top: 0}