I have something like :
var array = [ {'a':3,'b':4}, {'a':1,'b':8}, {'a':9,'b':7}] What is an elegant one line to find the min/max of the key 'a' (max=9, min = 1) ? I know it is simple but i couldn't find a one line solution only loops.
Logic
const array = [{ a: 3, b: 4 },{ a: 1, b: 8 },{ a: 9, b: 7 }]; const max = Math.max(...array.map(({ a }) => a)); console.log(max); Apply the same logic for min as well and use Math.min
const array = [{ a: 3, b: 4 },{ a: 1, b: 8 },{ a: 9, b: 7 }]; const nodes = array.map(({ a }) => a); const maxMin = { max: Math.max(...nodes), min: Math.min(...nodes)}; console.log(maxMin); you can do something like this
var array = [ { a: 3, b: 4 }, { a: 1, b: 8 }, { a: 9, b: 7 }, ]; const arrayA = array.map((v) => v.a); const maxA = Math.max(...arrayA); const minA = Math.min(...arrayA); console.log({ minA, maxA });
1or9or{ a: 9, b: 7 }or{ a: 1, b: 8 }or{ min: 1, max: 9 }or{ min: { a: 1, b: 8 }, max: { a: 9, b: 7 } }or something else? Countless options, no example, no effort, no surprise it got downvoted.const [min, max] = array.reduce(([min, max], { a }) => [a < min ? a : min, a > max ? a : max], [Infinity, -Infinity]).