Home > Net >  How to get a specific value out of a JavaScript function?
How to get a specific value out of a JavaScript function?

Time:06-02

I have a simple code which returns the highest number value from an array.

const getMax = (data) => Object.entries(data).reduce((max, item) => max[1] > item[1] ? max : item);

var myData1 = { a: 1, b:2, c: 3};
var myData2 = { a: 4, b:2, c: 3};

console.log(getMax(myData1));
console.log(getMax(myData2));

Return result:

[ 'c', 3 ]
[ 'a', 4 ]

This whole function is important to run for other purposes, but please how would I specifically print the output of only first calculated value (so 'c' or 'a') and then print specifically output of the second value (so 3 or 4)?

Thank you.

CodePudding user response:

A function can only return one value, whether simple or complex. You can store the complex value that a function returns, then use its individual simpler pieces:

const getMax = (data) => Object.entries(data).reduce((max, item) => max[1] > item[1] ? max : item);

var myData1 = { a: 1, b:2, c: 3};
var myData2 = { a: 4, b:2, c: 3};
var result1 = getMax(myData1);
var result2 = getMax(myData1);
var simple1_0 = result1[0];
var simple1_1 = result1[1];
var simple2_0 = result2[0];
var simple2_1 = result2[1];
console.log(simple1_0);
console.log(simple1_1);
console.log(simple2_0);
console.log(simple2_1);

  • Related