0

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

2
  • 1
    Why the output has 1.36 when there is a 1.35? Commented May 30, 2021 at 17:05
  • 1
    what you tried to solve your problem ? Commented May 30, 2021 at 17:05

2 Answers 2

2

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

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

Comments

1

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

Comments

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.