Top n max value from array of object JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say, we have an array of objects like this −

const arr = [
   {"id":0,"start":0,"duration":117,"slide":4,"view":0},
   {"id":0,"start":0,"duration":12,"slide":1,"view":0},
   {"id":0,"start":0,"duration":41,"slide":2,"view":0},
   {"id":0,"start":0,"duration":29,"slide":3,"view":0},
   {"id":0,"start":0,"duration":123,"slide":3,"view":0},
   {"id":0,"start":0,"duration":417,"slide":2,"view":0},
   {"id":0,"start":0,"duration":12,"slide":1,"view":0},
   {"id":0,"start":0,"duration":67,"slide":2,"view":0}
];

We have to write a function that takes in this array and returns the top n element of the array in another array (top means the object that has the highest value for duration).

Therefore, let’s write the code for this problem −

Example

const arr = [
   {"id":0,"start":0,"duration":117,"slide":4,"view":0},
   {"id":0,"start":0,"duration":12,"slide":1,"view":0},
   {"id":0,"start":0,"duration":41,"slide":2,"view":0},
   {"id":0,"start":0,"duration":29,"slide":3,"view":0},
   {"id":0,"start":0,"duration":123,"slide":3,"view":0},
   {"id":0,"start":0,"duration":417,"slide":2,"view":0},
   {"id":0,"start":0,"duration":12,"slide":1,"view":0},
   {"id":0,"start":0,"duration":67,"slide":2,"view":0}
];
const topN = (arr, n) => {
   if(n > arr.length){
      return false;
   }
   return arr
   .slice()
   .sort((a, b) => {
      return b.duration - a.duration
   })
   .slice(0, n);
};
console.log(topN(arr, 3));
console.log(topN(arr, 4));
console.log(topN(arr, 5));

Output

The output in the console will be −

[
   { id: 0, start: 0, duration: 417, slide: 2, view: 0 },
   { id: 0, start: 0, duration: 123, slide: 3, view: 0 },
   { id: 0, start: 0, duration: 117, slide: 4, view: 0 }
]
[
   { id: 0, start: 0, duration: 417, slide: 2, view: 0 },
   { id: 0, start: 0, duration: 123, slide: 3, view: 0 },
   { id: 0, start: 0, duration: 117, slide: 4, view: 0 },
   { id: 0, start: 0, duration: 67, slide: 2, view: 0 }
]
[
   { id: 0, start: 0, duration: 417, slide: 2, view: 0 },
   { id: 0, start: 0, duration: 123, slide: 3, view: 0 },
   { id: 0, start: 0, duration: 117, slide: 4, view: 0 },
   { id: 0, start: 0, duration: 67, slide: 2, view: 0 },
   { id: 0, start: 0, duration: 41, slide: 2, view: 0 }
]
raja
Published on 26-Aug-2020 15:09:30
Advertisements