1

I need to find matrices where all the values are the same. How should I go through the array to compare the values?

Example true:

[{"id": 1 ,"value": cow},{"id": 1 ,"value": cow},{"id": 1 ,"value": cow}] // true

Example false:

[{"id": 1 ,"value": cow},{"id": 2 ,"value": cat},{"id": 1 ,"value": cow}] // false

Thanks

3 Answers3

2

You can just compare every element of the array with the first one and if all of them are equal to it, then it means that every element in the array is the same:

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);
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
1

You can also do it like that

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);
Tom Adams
  • 61
  • 4
1

If the objects inside the array look just like yours then you've got your answer. But if you have a lot of properties rather than just id and value then you can try this:

// 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}
Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30