Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

객체 JavaScript 배열의 상위 n개 최대값

<시간/>

다음과 같은 객체 배열이 있다고 가정해 보겠습니다. -

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}
];

우리는 이 배열을 받아서 배열의 상위 n개 요소를 다른 배열로 반환하는 함수를 작성해야 합니다(top은 지속 시간 동안 가장 높은 값을 갖는 객체를 의미합니다).

따라서 이 문제에 대한 코드를 작성해 보겠습니다 -

예시

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));

출력

콘솔의 출력은 -

[
   { 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 }
]