Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

arrays - Returning a tuple in Javascript

I have an array of pokemon objects which have a Max and Min height (see snapshot below) and I need to return the average minimum and maximum height for all pokemon in the form of a tuple

const allPokemon = [
  {
    Height: {
      Minimum: '0.61m',
      Maximum: '0.79m',
    },
  },
];

I need to use HOFs so I was thinking to do something like this for both Maximum and Minimum height:

allPokemon.reduce((acc, cur) => acc + parseInt(cur.Height.Maximum), 0) / allPokemon.length;
allPokemon.reduce((acc, cur) => acc + parseInt(cur.Height.Minimum), 0) / allPokemon.length;

but I'm not sure how to return the two values in the form of a tuple (create empty array and push the values in? Concat method?)

Any help would be much appreciated.

question from:https://stackoverflow.com/questions/65842847/returning-a-tuple-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For now, JavaScript doesn’t have tuples. Besides, Javascript is weakly typed

Weakly typed means the compiler, if applicable, doesn't enforce correct typing. Without implicit compiler interjection, the instruction will error during run-time.

However, with the object or array destructuring you can archive it

  1. You can use .reduce with initial data as object like { Maximum: 0, Minimum: 0 } to aggregate your data like below:

const allPokemon = [
        {
          Height: {
            Minimum: "1.61m",
            Maximum: "2.79m"
           }
        }]
        
var result = allPokemon.reduce((acc, cur) => {
      acc.Maximum += (parseFloat(cur.Height.Maximum)/allPokemon.length);      
      acc.Minimum += (parseFloat(cur.Height.Minimum)/allPokemon.length);
      
      return acc; 
}, { Maximum: 0, Minimum: 0 });

console.log(result);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...