I'm currently still learning the basic JS and wondering how to answer this array type of question.
Question :
Given the participant's score sheet for your University Sports Day, You are required to find the runner-up score. You are given N scores. Store them in a list and find the score of the runner-up.
Input Format :
The first line contains N. The second line contains an array A[] of N integers each separated by a space.
Sample Input: [5,2,3,6,6,5]
Output Format :
Print the runner-up score.
Sample Output: 5
This is my code :
function uniqueScore (value, index, self) {
return self.indexOf(value) === index
}
var score = [5,2,3,6,6,5]
var filter = score.filter(uniqueScore)
var descSort = filter.sort().reverse()
function runnerUpScore(x) {
var runnerUp = descSort
return runnerUp
}
console.log(runnerUpScore(x))
The condition is I'm stuck when already sorting the array and removing duplicate. Hence, I need some guidance how to call the sorted array and only showing the index 1 from array list to show the runner up score.
The problem with your approach is you are sorting the array and then reversing it which costs lots of computation. Here is a simple solution in O(n). It iterates the array only once and finds the second-largest score, which is the runner-up score.
var scores = [1,2,3,4,5];
const runnerUpScore = (scores) => {
scores = [... new Set(scores)] // get unique elements
var largest = -1;
var secondLargest = -1;
scores.forEach((score) => {
if(score >= largest) {
secondLargest = largest;
largest = score;
} else if (score > secondLargest) {
secondLargest = score;
}
});
return secondLargest;
}
console.log(runnerUpScore(scores));
.sort() reverse:
let scores = [5, 2, 3, 6, 6, 5];
let reverseOrder = scores.sort((a, b) => b - a);
// [6, 6, 5, 5, 3, 2]
Set() then back to an array:
let set = new Set(reverseOrder)
// {6:6, 5:5, 3:3, 2:2} this is a representation there's much more to a Set.
let unique = [...set]
// [6, 5, 3, 2]
unique[1]
// 5
const scores = [5, 2, 3, 6, 6, 5];
const reverseOrderUnique = [...new Set(scores.sort((a, b) => b - a))];
console.log(reverseOrderUnique);
console.log('Runner Up: '+reverseOrderUnique[1]);
You can simply achieve it by sort the array in descending order by using Array.sort() and filtered out the duplicates by using Set() method and then access the runner-up score from 1st index of the array.
Live Demo :
// Input array
const scores = [5,2,3,6,6,5];
// Sort the array in descending order and remove the duplicates by using Set() method.
const sortedScores = [...new Set(scores.sort((a,b) => b-a))];
// Runner Up score by accesing the 1st index value.
console.log(sortedScores[1]);