-5

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.

11
  • 1
    So what is the result, precisely? 1 or 9 or { 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. Commented Dec 21, 2022 at 8:54
  • 6
    I wish the new generation of JS coders stopped looking for inefficient one liners and focus on performance and readability.. Wait, did I just made an old man rant? Commented Dec 21, 2022 at 8:55
  • 1
    @gotiredofcoding Not my downvote, but people do tent to downvote questions that don't show any effort, as they come across like "do my work for me" questions. Commented Dec 21, 2022 at 8:55
  • 1
    Here's a useless solution that only traverses the array once to get both min and max: const [min, max] = array.reduce(([min, max], { a }) => [a < min ? a : min, a > max ? a : max], [Infinity, -Infinity]). Commented Dec 21, 2022 at 9:06
  • 1
    > calls us childish > engages in childish behavior in response to valid criticism about the nature of your question wut Commented Dec 21, 2022 at 9:13

3 Answers 3

2

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);

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

Comments

1

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 });

2 Comments

Technically it's not a one-liner, though.
"do something like this" without explanatory commentary isn't particularly useful.
0

Tried to keep it in 1 line.

var array = [ { a: 3, b: 4 }, { a: 1, b: 8 }, { a: 9, b: 7 }, ]; const result = { min: Math.min(...array.map((x) => x.a)), max: Math.max(...array.map((x) => x.a)), }; console.log(result);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.