繁体   English   中英

验证数组中的值是否相同或不同

[英]Verify that the values within an array are the same or different

我需要找到所有值都相同的矩阵。 我应该如何通过数组来比较 go 的值?

例真:

[{"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

谢谢

您可以将数组的每个元素与第一个元素进行比较,如果它们都相等,则意味着数组中的每个元素都是相同的:

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

你也可以这样做

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

如果数组中的对象看起来和你的一样,那么你已经得到了答案。 但是如果你有很多属性而不仅仅是idvalue那么你可以试试这个:

 // 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}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM