0

I have an array of dictionaries and I am trying to fetch the dictionary with the highest value from the array.

const array = [{"value": 1}, {"value": 3}, {"value": 2}]

I want to fetch {"value": 3} since its "value" key has the highest value.

What is the most elegant way of achieving this in TypeScript? I thought about sorting the array first by the value key but even that seems to be a pain.

etayluz
  • 15,920
  • 23
  • 106
  • 151
  • 1
    1. "*Why do people like TypeScript so much anyway?*" how is that relevant to the question? 2. How is this a TypeScript question? It'd be the same in JS or TS. Adding types doesn't change the algorithm you want – VLAZ Apr 27 '21 at 17:03
  • @VLAZ I'm sorry if I offended you. What is the Javascript way then? I'm looking for some cool higher order function here – etayluz Apr 27 '21 at 17:08
  • It's a simple `.reduce()` over the dataset always keeping the higher of the two objects and passing it off to the next iteration. Guaranteed `O(n)` with a single pass. – VLAZ Apr 27 '21 at 17:10
  • @VLAZ very cool! Can you write out the answer in code? – etayluz Apr 27 '21 at 17:14
  • 3
    `array.reduce((highest, current) => current.value > highest.value ? current : highest)`. If you want to make sure it works on empty arrays without throwing an error and without extra checks, you can add an initial value: `{value: -Infinity}` – VLAZ Apr 27 '21 at 17:19

1 Answers1

1

You can do it like this. Playground

   interface Value {
    value: number;
}

    const array:Value[] = [{ "value": 1 }, { "value": 3 }, { "value": 11 }, { "value": 0 }, { "value": 8 }, { "value": 10 }];
    
    const greatest = array.reduce((accumulator: Value, element: Value) => {
        if (accumulator["value"] > element["value"])
            return accumulator;
        return element;
    });
    
    console.log(greatest);
Syed Mohib Uddin
  • 718
  • 7
  • 16