W
W
wakenbyWork2021-07-02 16:10:47
JavaScript
wakenbyWork, 2021-07-02 16:10:47

How to leave the three largest numbers in an object?

There is an object like this:

const object = {
  1: 1,
  2: 3,
  3: 3,
  4: 3,
  5: 0,
  6: 2,
  7: 1,
  8: 3
}


Ie keys from 1 to 8, and their values. It is necessary to leave 3 keys (i.e. leave key=value) with the largest values

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-07-02
@wakenbyWork

We collect a new object:

const newObj = Object.fromEntries(Object
  .entries(obj)
  .sort((a, b) => a[1] - b[1])
  .slice(-3)
);

Delete the properties of an existing one:
Object
  .entries(obj)
  .sort((a, b) => b[1] - a[1])
  .slice(3)
  .forEach(n => delete obj[n[0]]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question