Reputation: 27
How can I easily get the array the contains the min and max values from a 2d array in JavaScript?
Below you can find the dateset. I only want to check the min and max values of the second element (eg 1.40, 1.38, 1.35).
[1622306648284, 1.4025036293793085],
[1622309604992, 1.384071162873584],
[1622312530257, 1.3503030062861177],
[1622315654724, 1.3625441847416848],
[1622318703104, 1.3645747739529213],
[1622321575558, 1.3611235799170127],
[1622324539379, 1.3750838657128996],
[1622327549644, 1.378768535066251],
[1622330652746, 1.3916061750979443],
[1622333538315, 1.4076792700030256],
[1622336466156, 1.3674852893896725]
So the expected output will be.
Min: [1622321575558, 1.3503030062861177] Max: [1622333538315, 1.4076792700030256]
Thanks
Upvotes: 0
Views: 396
Reputation: 386868
You could reduce the array by using an object with min and max values.
const
data = [[1622306648284, 1.4025036293793085], [1622309604992, 1.384071162873584], [1622312530257, 1.3503030062861177], [1622315654724, 1.3625441847416848], [1622318703104, 1.3645747739529213], [1622321575558, 1.3611235799170127], [1622324539379, 1.3750838657128996], [1622327549644, 1.378768535066251], [1622330652746, 1.3916061750979443], [1622333538315, 1.4076792700030256], [1622336466156, 1.3674852893896725]],
result = data.reduce(({ min, max }, a) => {
if (a[1] < min[1]) min = a;
if (a[1] > max[1]) max = a;
return { min, max };
}, { min: [, Number.MAX_VALUE], max: [, -Number.MAX_VALUE] });
console.log(result);
Upvotes: 1
Reputation: 1404
The output you wanted is strange, but this does the trick.
const arr = [[1622306648284, 1.4025036293793085],[1622309604992, 1.384071162873584],[1622312530257, 1.3503030062861177],[1622315654724, 1.3625441847416848],[1622318703104, 1.3645747739529213],[1622321575558, 1.3611235799170127],[1622324539379, 1.3750838657128996],[1622327549644, 1.378768535066251],[1622330652746, 1.3916061750979443],[1622333538315, 1.4076792700030256],[1622336466156, 1.3674852893896725]];
const max = arr.reduce((a, b) => a[1] >= b[1] ? a : b);
const min = arr.reduce((a, b) => a[1] <= b[1] ? a : b);
console.log(`Min: ${min} Max: ${max}`);
Upvotes: 2