0

Sample array

var myItems = [{height:500, width:400},{height:500, width:800},{height:500, width:700}]

Instead of doing

if(myItems[0].height !== myItems[1].height && myItems[0].height !== myItems[2].height && myItems[1].height !== myItems[2].height){
 // do smth about it
}

with larger arrays this code gonna get ridiculous, so I played with this

if (myItems.reduce((x,y)=>x.height!==y.height)){
 // do the same thing
}

The problem is, this always returns true even if the above values are in place, all items have same height value.

thednp
  • 4,401
  • 4
  • 33
  • 45
  • what is the result of all? – Nina Scholz Jul 02 '20 at 15:38
  • 2
    This is not how `reduce` works. The first argument in the function is an _aggregator_, the second argument is the next item. The initial value of the aggregator is taken from the second argument passed to `reduce`, or the first item in the array; you might want to start with a boolean value instead of an object. It looks like you’re asking for an n² comparison (every object with every object) rather than a sequential one, so this won’t work with a single `reduce`. – Sebastian Simon Jul 02 '20 at 15:39
  • Check [this post](https://stackoverflow.com/q/62461165/13638059) it might help you – Ehsan Nazeri Jul 02 '20 at 15:40
  • @user4642212 I'm open to any suggestion on how that might look like. – thednp Jul 02 '20 at 16:00

1 Answers1

0

You can try converting this to a set for height and then compare the lengths for your array and the heightSet.

var myItems = [{height:500, width:400},{height:500, width:800},{height:500, width:700}];

var heightSet = [...new Set(myItems.map(x => x.height))];

console.log(myItems.length === heightSet.length);