1

This question does it in Javascript, but I would have thought in Typescript I could do some kind of map/filter operation to do the same thing.

I have an array of objects called Room. Each Room has a property called Width (which is actually a string, eg '4m', '5m', '6.5m').

I need to check the entire array to see if all the widths are the same.

Based on that question I have this, but I was wondering if TypeScript has something better:

let areWidthsTheSame = true;
this.qp.rooms.forEach(function(room, index, rooms) {
  if (rooms[index] != rooms[index+1]) areWidthsTheSame = false;
});  

Any ideas?

FYI the linked question has a comment that links to these performance tests, which are interesting in the context of this question:

Community
  • 1
  • 1
rmcsharry
  • 5,363
  • 6
  • 65
  • 108

1 Answers1

2

This can be done in the following way:

const widthArr = rooms.map(r => r.width);
const isSameWidth = widthArr.length === 0 ? true :
                          widthArr.every(val => val === widthArr[0]);

We first convert the rooms array to an array of widths and then we check if all values in widths arrays are equal.

galvan
  • 7,400
  • 7
  • 38
  • 55
  • Nice - I think you can make it one line, right? const isSameWidth = rooms.map(r => r.width).every(val => val === rooms[0].width); – rmcsharry Mar 16 '17 at 14:37
  • No, because we acessing the first index so if the array is empty you'll get an exception, if you are 100% sure that there are rooms in your array then you are safe to do this @rmcsharry – galvan Mar 16 '17 at 14:40