Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

get highest element in a two dimensional array

i have this array:

const myArray = [["Cow", 3], ["Pig", 5], ["Pig", 10], ["Pig", 4], ["Chicken", 1], ["Cow", 1], ["Cow" , 12], ["Cow", 11], ["Chicken", 12]]

and want to turn into this: (only the highest of each one)

[ [ 'Pig', 10 ], [ 'Cow', 12 ], [ 'Chicken', 12 ] ]

but with my code i cant get the last one, i cant find why tho

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const myArray = [["Cow", 3], ["Pig", 5], ["Pig", 10], ["Pig", 4], ["Chicken", 1], ["Cow", 1], ["Cow" , 12], ["Cow", 11], ["Chicken", 12]]

function getHighest() {

  var onlyHighest = [];

  myArray.sort(
    function(a,b) {
      if (a[0] == b[0])
       return a[1] < b[1] ? -1 : 1;
      return a[0] < b[0] ? 1 : -1;
    }
  );  

  myArray.forEach((a, i) => {
    var i = i+1;
    if (i < myArray.length) {
      if (a[0] != myArray[i][0]){
        onlyHighest.push([a[0], a[1]]);
      }
    }
  });

  return console.log(onlyHighest)
  //    [ [ 'Pig', 10 ], [ 'Cow', 12 ] ]
}

>Solution :

Use an object to hold the current highest value for each animal. Loop through the array, replacing the value when it’s higher than the value in the object.

const myArray = [["Cow", 3], ["Pig", 5], ["Pig", 10], ["Pig", 4], ["Chicken", 1], ["Cow", 1], ["Cow" , 12], ["Cow", 11], ["Chicken", 12]]

function getHighest(array) {
  let obj = {};
  array.forEach(([key, value]) => {
    if (key in obj) {
      if (value > obj[key]) {
        obj[key] = value;
      }
    } else {
      obj[key] = value;
    }
  });
  return Object.entries(obj);
}

console.log(getHighest(myArray));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading