codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

JavaScript: Finding Minimum and Maximum values in an Array of Objects

Brandon Morelli
codeburst
Published in
6 min readJul 30, 2017

Numbers. Photo by Paul Bergmeir

The Problem.

[
{x: 1, y: 14830},
{x: 2, y: 85055},
{x: 3, y: 03485},
{x: 4, y: 57885},
// ...
]

The ‘Why’.

stupid simple graph

The X Values.

stupid simple graph

The Y Values.

stupid simple graph

Testing.

const data = []for (let x = 1; x <= 100000; x++) {
data.push({ x: x, y: Math.floor(Math.random() * (1000000)) })
}
// RETURNS THE DATA BELOW:[
{x: 1, y: 14830},
{x: 2, y: 85055},
{x: 3, y: 03485},
{x: 4, y: 57885},
// ...
]

The Solutions.

1. Using reduce()

let sum = [1, 2, 3].reduce((total, num) => total + num, 0);
// sum === 6
// [1, 2, 3].reduce((total, num) => total + num, 0)
// [1, 2, 3].reduce((0, 1) => 0 + 1)
// [2, 3].reduce((1, 2) => 1 + 2)
// [3].reduce((3, 3) => 3 + 3)
// 6
function getMinY() {
return data.reduce((min, p) => p.y < min ? p.y : min, data[0].y);
}
function getMaxY() {
return data.reduce((max, p) => p.y > max ? p.y : max, data[0].y);
}

2. Using map(), Math, and the spread operator

function getYs(){
return data.map(d => d.y);
}
function getMinY(){
return Math.min(...getYs());
}
function getMaxY(){
return Math.max(...getYs());
}

3. Why not both?

function getMinY(){
return data.reduce((min, b) => Math.min(min, b.y), data[0].y);
}
function getMaxY(){
return data.reduce((max, b) => Math.max(max, b.y), data[0].y);
}

The Fastest Option?

function findMinMax(arr) {
let min = arr[0].y, max = arr[0].y;

for (let i = 1, len=arr.length; i < len; i++) {
let v = arr[i].y;
min = (v < min) ? v : min;
max = (v > max) ? v : max;
}

return [min, max];
}

Want more React?

What do you think?

Check out my recent articles:

If this post was helpful, please click the clap 👏button below a few times to show your support! ⬇⬇

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Brandon Morelli

Creator of @codeburstio — Frequently posting web development tutorials & articles. Follow me on Twitter too: @BrandonMorelli

Responses (10)

Write a response