1

I have an object array in my angular (typescript) Project.

let a = [{min:0, max:10},{min:10, max:810},{min:-10, max:110}];

So I want to get minimum of min, and maximum of the max items. I need two variables like following:

let min = // minimum of all items min property = -10;
let max = // maximum of all items max property = 810;

can I do this using lambda or other ways practically?

3 Answers 3

1

You can use map to get all min/max values. Use Math.min and Math.max to get the values.

let a = [{min:0, max:10},{min:10, max:810},{min:-10, max:110}];

let min = Math.min(...a.map(o => o.min));
let max = Math.max(...a.map(o => o.max));

console.log(min);
console.log(max);

Another option is using reduce. This option only needs to loop the array once.

let a = [{min:0, max:10},{min:10, max:810},{min:-10, max:110}];

let min = a.reduce((c, v) => v.min < c ? v.min : c, 0);
let max = a.reduce((c, v) => v.max > c ? v.max : c, 0);

console.log(min);
console.log(max);

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

2 Comments

what means "..." in front of a.map?
1
let min = Math.min(...a.map((item)=>{return item.min}))
let max = Math.max(...a.map((item)=>{return item.max}))

Comments

0

Try this:

 let a = [{min:0, max:10},{min:10, max:810},{min:-10, max:110}];

    let min = Math.min(...a.map(value => value.min));
    let max = Math.max(...a.map(value => value.max));

1 Comment

_is a library that is not part of native javaScript. If using underscore this would be a good answer. However, since OP is not asking about underscore/lodash I think this answer is not correct.

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.