0

I have an array of objects like so:

const data = [
    { depth: 0, length: 5 },
    { depth: 1, length: 8 },
    { depth: 1, length: 11 },
    { depth: 1, length: 6 },
    { depth: 1, length: 8 },
    { depth: 1, length: 11 },
    { depth: 1, length: 6 },
    { depth: 1, length: 8 },
    { depth: 2, length: 16 },
    { depth: 2, length: 25 }
];

I need to get the highest length value per depth key. The array I want is:

const result = [
    { depth: 0, length: 5 },
    { depth: 1, length: 11 },
    { depth: 2, length: 25 }
];

The data array can be X depths deep. Other examples I have seen only get the highest value, or single object with the highest value, whereas I need the highest value per key.

Thanks!

1

1 Answer 1

0

Reduce the array to a Map using the depth as key. If the current object doesn't exist in the Map, or the current length is the Map is less then the current item's length, store the item for that depth. Convert to an array by spreading the Map's value iterator:

const data = [{"depth":0,"length":5},{"depth":1,"length":8},{"depth":1,"length":11},{"depth":1,"length":6},{"depth":1,"length":8},{"depth":1,"length":11},{"depth":1,"length":6},{"depth":1,"length":8},{"depth":2,"length":16},{"depth":2,"length":25}];

const result = [...data.reduce((r, o) =>
  (!r.has(o.depth) || r.get(o.depth).length < o.length) ? r.set(o.depth, o) : r
, new Map()).values()];

console.log(result);

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

1 Comment

Thanks! exactly what I needed

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.