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:

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Nice - I think you can make it one line, right? const isSameWidth = rooms.map(r => r.width).every(val => val === rooms[0].width);
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.