Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

kth largest element(string) in an array based on length

I need to find the kth largest element in an array(of strings) and return them according to the rank.

Example –

Input

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var array = ['java','python','javascript','C','Swift','Dart'];

Expected Output

[['javascript', 1],
 ['python', 2],
 ['Swift', 3],
 ['java', 4],
 ['Dart', 4],
 ['C', 5]]

I tried this –

var rank = 0
var result = []
var arr = ['java','python','javascript','C','Swift','Dart'];
arr.sort((a,b)=>b.length-a.length);
for(let i=0;i<arr.length;i++){
        if(arr[i+1]===undefined){
            break;
        }
        else if (arr[i].length>arr[i+1].length){
        ++rank} 
       result.push([arr[i],rank])
}
console.log(JSON.stringify(result))

But as you can see, it dint work. How do I approach this? A little help, please.

>Solution :

const arr = ['java','python','javascript','C','Swift','Dart'];
arr.sort((a, b) => b.length - a.length)
const res = arr.reduce((acc, el) => {acc.push([el, acc.length == 0 ? 1 : el.length == acc[acc.length-1][0].length ? acc[acc.length-1][1] : acc[acc.length-1][1]+1]); return acc}, [])
console.log(JSON.stringify(res))

If you want to do it your way, you can do something like the following:

let rank = 1
const arr = ['java','python','javascript','C','Swift','Dart'];
arr.sort((a,b)=>b.length-a.length);
const result = [[arr[0], 1]]
for(let i=1;i<arr.length;i++){
        if (arr[i].length<arr[i-1].length){
        ++rank} 
       result.push([arr[i],rank])
}
console.log(JSON.stringify(result))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading